Home > Net >  Apply ColorFiltered to a container
Apply ColorFiltered to a container

Time:12-02

I want to apply the widget ColorFiltered to a container which is inside an other container, the problem is the filter takes all the screen => The filter is also applied to the blue container, and this same container expands.

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(body:Test1()),
    );
  }
}


class Test1 extends StatelessWidget {
  const Test1({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.blue,
        height: 300,
        width: MediaQuery.of(
          context,
        ).size.width,
        child: Align(
            child: ColorFiltered(
          colorFilter:
              const ColorFilter.mode(Colors.grey, BlendMode.saturation),
          child: Container(
            width: 100,
            height: 100,
            color: Colors.red,
          ),
        )));
  }
}

CodePudding user response:

It seems like a Flutter issue, tracked here.

One workaround suggested in the issue is to wrap the container in a ClipRect Widget like this:

class Test1 extends StatelessWidget {
  const Test1({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      height: 300,
      width: MediaQuery.of(context).size.width,
      child: Align(
        child: ClipRect(
          child: ColorFiltered(
            colorFilter:
                const ColorFilter.mode(Colors.grey, BlendMode.saturation),
            child: Container(
              width: 100,
              height: 100,
              color: Colors.red,
            ),
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

class TestWidget extends StatelessWidget {
  const TestWidget ({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.indigo,
      height: 300,
      width: MediaQuery.of(context).size.width,
      child: Align(
        child: ClipRect(
          child: ColorFiltered(
            colorFilter:
                const ColorFilter.mode(Colors.grey, BlendMode.saturation),
            child: Container(
              width: 100,
              height: 100,
              color: Colors.red,
            ),
          ),
        ),
      ),
    );
  }
}
  • Related