Making an Image widget disabled / grayed out

Set the widget as the child of a container, and add foregroundDecoration like this:

Container(
  foregroundDecoration: BoxDecoration(
    color: Colors.grey,
    backgroundBlendMode: BlendMode.saturation,
  ),
  child: child,
)

-- Update: Based on this new video from flutter team, there is another widget for this. The code is basically the same, and it is like this:

ColorFiltered(
  colorFilter: ColorFilter.mode(
    Colors.grey,
    BlendMode.saturation,
  ),
  child: child,
)

But I still prefer the method using Container forgroundDecoration, since container gives you more flexibilities in the same place.


If your child is a .png image, flutter will render it with a grey background if you put Colors.grey. Using the same color of your widget background you will have a perfect disabled image

ColorFiltered(
    colorFilter: ColorFilter.mode(
        Colors.white,
        BlendMode.saturation,
    ),
    child: child,
)

If you want to change the color of your image when user clicks it, you can do this:

GestureDetector(
    onTap: () => {
        setState((){
            _active = !_active;
        })
    },
    child: ColorFiltered(
        colorFilter: ColorFilter.mode(                                       
            _active ? Colors.transparent : Colors.white,                                                         
            BlendMode.saturation,

        ),
        child: Image(
            image: Image.asset("assets/test.png").image
        ),
    ),
)

I adapted Mark O'Sullivan post and created a general purpose widget:

To use it:

text = Text("Hellow World");
GrayedOut(text);

or

GrayedOut(text, grayedOut: true);

And the class

class GrayedOut extends StatelessWidget {
  final Widget child;
  final bool grayedOut;

  GrayedOut(this.child, {this.grayedOut = true});

  @override
  Widget build(BuildContext context) {
    return grayedOut ? new Opacity(opacity: 0.3, child: child) : child;
  }
}

According flutter documentation of ColorFiltered you can use ColorFilter.matrix link like this:

const ColorFilter greyscale = ColorFilter.matrix(<double>[
  0.2126, 0.7152, 0.0722, 0, 0,
  0.2126, 0.7152, 0.0722, 0, 0,
  0.2126, 0.7152, 0.0722, 0, 0,
  0,      0,      0,      1, 0,
]);

ColorFiltered(
  colorFilter: greyscale,
  child: child,
);

In this case ColorFilter will ignore transparent areas of your images.

Tags:

Flutter