Flutter color filling animation

Issue

I’m currently working on a flutter project and I was trying to reproduce this dynamic color filling effect:

enter image description here

I’ve tried to look at the Flutter documentation to see if there is some widget that let me "fill" the container with this color effect, but I didn’t find anything relevant.

Is there a way to do this in Flutter? If yes, could you please help me?
Thank you!

Solution

This is called an in-effect or Material ripples effect, and you can achieve it using the InkWell widget like this:

      Material(
            color: Colors.red,
            child: InkWell(
              splashColor: Colors.blue,
              onTap: () {},
              child: Container(
                width: 50,
                height: 50,
                child: Text("test"),
              ),
            ),
          ),

you can show that effect programmatically by the following.
first, create a GlobalKey:

final GlobalKey key = GlobalKey();

Then assign it to the InkWell widget so it will be like this:

      Material(
            color: Colors.red,
            child: InkWell(
              key: key,
              splashColor: Colors.blue,
              onTap: () {},
              child: Container(
                width: 50,
                height: 50,
                child: Text("test"),
              ),
            )

then, you can simulate tapping it from other places with this:

void simulateAClick() {
  RenderBox box = key.currentContext!.findRenderObject() as RenderBox;
  Offset position = box.localToGlobal(Offset.zero);

  WidgetsBinding.instance.handlePointerEvent(PointerDownEvent(
    pointer: 0,
    position: position,
  ));
  WidgetsBinding.instance.handlePointerEvent(PointerUpEvent(
    pointer: 0,
    position: position,
  ));
}

now when you run simulateAClick(), you should see a ink effect triggered in the InkWell

Answered By – Gwhyyy

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *