Search code examples
flutterflutter-animation

How to animate background color on ElevatedButton?


I would like to create a fade between two background colors when my ElevatedButton change his state to disable, how can I do that ?

final _buttonStyle = ElevatedButton.styleFrom(
  backgroundColor: Colors.white,
  disabledBackgroundColor: Colors.white.withOpacity(0.5),
  animationDuration: const Duration(milliseconds: 0),
  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
);

I see there is an animationDuration property, however it seems to only create a delay between the change of color. No animations are visible.


Solution

  • You can use AnimatedSwitcher . First define this out of build method:

    bool isVisible = false;
    

    then do this:

    AnimatedSwitcher(
              child: SizedBox(
                width: 100,
                key: UniqueKey(),
                child: ElevatedButton(
                  onPressed: () {
                    setState(() {
                      isVisible = !isVisible;
                    });
                  },
                  child: Text('click'),
                  style: ButtonStyle(
                      splashFactory: InkRipple.splashFactory,
                      overlayColor: MaterialStateProperty.resolveWith(
                      (states) {
                        return states.contains(MaterialState.pressed)
                            ? Colors.grey
                            : null;
                         },
                      ),
                      backgroundColor: MaterialStateProperty.all(
                          isVisible ? Colors.red : Colors.green)),
                ),
              ),
              duration: Duration(milliseconds: 500),
      ),
    

    enter image description here