如何为 ElevatedButton 上的背景颜色设置动画?

Jul*_*ata 4 flutter flutter-animation

当我的 ElevatedButton 将其状态更改为禁用时,我想在两种背景颜色之间创建淡入淡出,我该怎么做?

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

我看到有一个animationDuration属性,但它似乎只在颜色变化之间产生延迟。没有可见的动画。

eam*_*ein 5

您可以使用AnimatedSwitcher。首先定义这个构建方法:

bool isVisible = false;
Run Code Online (Sandbox Code Playgroud)

然后这样做:

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),
  ),
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述