Home > Net >  How to animate background color on ElevatedButton?
How to animate background color on ElevatedButton?

Time:09-09

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.

CodePudding user response:

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

CodePudding user response:

One way you can achieve similar behavior without ElevatedButton is like so, by using AnimatedContainer and InkWell

//define a state variable
bool disableButton = false;

//build the button like so
InkWell(
  onTap: disableButton ? null : () => print('Button tapped'),
  child: AnimatedContainer(
    duration: const Duration(milliseconds: 600),
    decoration: BoxDecoration(
      color: disableButton ? Colors.grey : Colors.blue,
      borderRadius: BorderRadius.circular(10),
    ),
    padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 6),
    child: Text('Abc'),
  ),
)

//make disableButton true to disable the button
setState(() => disableButton = true);
  • Related