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:

var isVisible = false;

then do this:

AnimatedSwitcher(
              child: isVisible
                  ? ElevatedButton(
                      key: UniqueKey(),
                      onPressed: () {
                        setState(() {
                          isVisible = false;
                        });
                      },
                      child: Text('click'),
                      style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(Colors.red)),
                    )
                  : ElevatedButton(
                      key: UniqueKey(),
                      onPressed: () {
                        setState(() {
                          isVisible = true;
                        });
                      },
                      child: Text('click'),
                      style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(Colors.green)),
                    ),
              duration: Duration(milliseconds: 500),
            ),

enter image description here

Leave a Reply