40

I have a bunch of Image widgets which when in a disabled state, should look grayed out.

Is there a way to alter an existing image make it look disabled / grayed out?

I want to avoid having both an enabled image asset and a disabled image asset increasing the overall APK size instead of having the single asset.

13 Answers 13

110

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.

7
  • can I adjust the grey value for lighter grey?
    – stan liu
    Nov 4, 2019 at 8:04
  • 1
    Unfortunately, this seems to apply the filter over the background of the image too. Is there a way to avoid that?
    – Tin Man
    Nov 22, 2019 at 13:50
  • @TinMan check the video link I added in the update section. Use the color parameter in the image.Asset widget. Nov 28, 2019 at 13:18
  • @stanliu sure, you can change the colour to whatever you want. :) Nov 28, 2019 at 13:29
  • 1
    @SinaSeirafi Unfortunately, ColorFiltered still doesn't handle transparency :(
    – Tin Man
    Dec 2, 2019 at 21:53
27

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.

2
  • For transparent images, this is the simplest approach (for now at least).
    – Mjaustro
    Sep 12, 2020 at 0:39
  • How do you lerp this to zero effect so we can lerp saturated to desaturated? Nov 20 at 1:40
13

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
        ),
    ),
)
11

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;
  }
}
1
  • 2
    This solution is not what OP asked, instead it just wraps an Opacity widget. If you apply it to a colored image, that won't be grayed out but merely faded.
    – Zimes
    May 12, 2020 at 7:43
7

From my own personal experiences I've found combining a color filter along with Opacity works well in giving a disabled state to an Image.

enter image description here

Shown above is an example of one of my enabled images.

enter image description here

Shown above is what that image looks like looks like whenever you apply a color filter and add Opacity widget to your image.

For you to implement something similar you would need this code:

  new Material(
      elevation: 2.0,
      child: new Opacity(
        opacity: 0.3,
        child: new Container(
          padding: new EdgeInsets.all(20.0),
          child: new Image.asset("assets/<your icon>", fit: BoxFit.cover, color: Colors.grey),
          decoration: new BoxDecoration(
            border: new Border.all(
              width: 2.0, color: const Color(0x40000000)),
              borderRadius: const BorderRadius.all(const Radius.circular(5.0)
            )
          )
        )
      )
  );
0
5

This widget implements what the Google Flutter engineer @dnfield said on this Flutter GitHub issue, which works with images with transparent background.

import 'package:flutter/widgets.dart';

class GrayscaleColorFiltered extends StatelessWidget {
  final Widget child;

  const GrayscaleColorFiltered({Key? key, required this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ColorFiltered(
      colorFilter: 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,
      ]),
      child: child,
    );
  }
}

2
  • 1
    This should be the accepted answer because it perfectly avoids to mess up transparency of child.
    – wangpan
    Nov 30, 2021 at 9:18
  • Glad you think that, @wangpan! :·) Dec 1, 2021 at 10:57
3

Screenshot:

enter image description here

enter image description here


Code:

ColorFiltered(
  colorFilter: ColorFilter.mode(
    Colors.black.withOpacity(0.5), // 0 = Colored, 1 = Black & White
    BlendMode.saturation,
  ),
  child: Image.asset(
    'chocolate_image',
    fit: BoxFit.cover,
  ),
)

Source

2

I created a Widget based on Marks answer above:

import 'package:flutter/material.dart';

class DisabledRenderer extends StatelessWidget {
  final Widget child;
  final bool enabled;
  final double padding;
  final double boxWidth;
  final Color boxColor;
  final double boxRadius;

  DisabledRenderer(
      {@required this.child,
      @required this.enabled,
      this.padding = 2,
      this.boxWidth = 2,
      this.boxColor = Colors.white,
      this.boxRadius = 5.0});

  @override
  Widget build(BuildContext context) => Material(
        elevation: 2.0,
        child: Opacity(
          opacity: enabled ? 1 : 0.3,
          child: Container(
            padding: EdgeInsets.all(padding),
            child: child,
            decoration: BoxDecoration(
              border: Border.all(width: boxWidth, color: boxColor),
              borderRadius: BorderRadius.all(Radius.circular(boxRadius)),
            ),
          ),
        ),
      );
}

In use it looks like that:

DisabledRenderer(enabled: false, child: Icon(MdiIcons()['speedometer'],);

The enable bool is usually used with a StreamBuilder to listen to a model event. How to do that please search for Flutter Bloc pattern and StreamBuilder

If you need a version which supports streams (bloc pattern) then use this one:

import 'package:flutter/material.dart';

class DisabledRenderer extends StatelessWidget {
  final Widget child;
  final bool enabled;
  final Stream enableStream;
  final double padding;
  final bool showBorder;
  final double boxWidth;
  final Color boxColor;
  final double boxRadius;

  DisabledRenderer(
      {@required this.child,
      this.enabled,
      this.enableStream,
      this.showBorder = true,
      this.padding = 2,
      this.boxWidth = 2,
      this.boxColor = Colors.white,
      this.boxRadius = 5.0}) {
    //one or the other, not both
    assert((enableStream != null && enabled == null) ||
        (enableStream == null && enabled != null));
  }

  @override
  Widget build(BuildContext context) => Material(
        elevation: 2.0,
        child: enableStream != null
            ? StreamBuilder<bool>(
                initialData: false,
                stream: enableStream,
                builder: (BuildContext context, AsyncSnapshot enabled) {
                  return enabled.hasData
                      ? _renderEnabledDisabledState(enabled.data)
                      : Container();
                },
              )
            : _renderEnabledDisabledState(enabled),
      );

  Widget _renderEnabledDisabledState(bool enabled) {
    return IgnorePointer(
      ignoring: !enabled,
      child: Opacity(
        opacity: enabled ? 1 : 0.3,
        child: showBorder
            ? Container(
                padding: EdgeInsets.all(padding),
                child: child,
                decoration: BoxDecoration(
                  border: Border.all(width: boxWidth, color: boxColor),
                  borderRadius: BorderRadius.all(Radius.circular(boxRadius)),
                ),
              )
            : child,
      ),
    );
  }
}

this is how you would use it:

DisabledRenderer(
                 showBorder: false,
                 enableStream: BlocProvider.of(context)
                                      .bluetooth
                                      .isConnected
                                      .stream,
                 child: YourWidget(),
    ```



5
  • 1
    I do not mind if people vote down a solution. It would be nice if you could state briefly what the problem is and we can all learn from it because we make an honest effort here. Thank you.
    – Ride Sun
    Nov 11, 2019 at 18:48
  • Your widget looks coupled to your project. Why a stream is present in your class? And your code is not abstracting the complexity of your project. BTW: the downvote is not mine.
    – Juliano
    Jul 5, 2020 at 1:04
  • 1
    Its not coupled to my project. Its a generic examples . The enable state can come either from a enable bool or from a stream<bool>. streams are often used in Flutter / dart projects. The last example shows how I use it in my project but the widget itself is generic.
    – Ride Sun
    Jul 5, 2020 at 4:59
  • You are right, your component is not really coupled. It just feels strange to see a Stream of booleans in this kind of component, but I see you exposed a simple boolean as well.
    – Juliano
    Jul 6, 2020 at 2:31
  • If you use streams in your model you can directly consume it no StreamBuilder etc. Very handy.
    – Ride Sun
    Jul 6, 2020 at 4:50
1

To configure a custom grey color (or any other color) to a transparent image:

ColorFiltered(
  colorFilter: const ColorFilter.mode(
    Colors.grey, // or any other color
    BlendMode.srcATop,
  ),
  child: MyImage(),
),
0

However it is not possible directly. For runtime grayscale you can use a dart image package with flutter. Load your images with dart image package, apply grayscale function, read the bytes from grayscale image and use it with Image.memory widget of flutter.

You can just get bytes without applying grayscale for a coloured image.

Hope that helped!

0

I think this can be done using alpha, which can create effect of disabled. This trick works for dark and light theme too because it inherits from parent. I have used cardColor, you can choose any theme and apply the color.

Theme.of(context).cardColor.withAlpha(180)
0

You can do this easily by using BackDropFilter In below code I am bluring widget + adding grayscale. This solution will work even for dialog

BackdropFilter(
    filter: ImageFilter.compose(
      outer: ImageFilter.blur(sigmaX: 6, sigmaY: 6);,
      inner: const ColorFilter.mode(
        Colors.grey,
        BlendMode.saturation,
      ),
    ),
    child:AnyWidget(),
  );

enter image description here

0

used this

class GrayscaleColorFiltered extends StatelessWidget {
   final Widget child;

    const GrayscaleColorFiltered({Key? key, required this.child}) : 
  super(key: key);

 @override
  Widget build(BuildContext context) {
  return ColorFiltered(
  colorFilter: ColorFilter.mode(Colors.grey, 
 BlendMode.saturation),
  child: child,
);
}

its work for me

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.