【问题标题】:How to animate the color of a RaisedButton in Flutter?如何在 Flutter 中为 RaisedButton 的颜色设置动画?
【发布时间】:2019-04-30 10:08:17
【问题描述】:

我有一个RaisedButton。我想动画它的颜色从绿色红色,反之亦然,每次用户点击它。

如何做到这一点?

【问题讨论】:

  • ColorTween
  • 我知道 ColorTween,但我不知道如何将它应用到凸起按钮上。你能提供更多细节吗?
  • 例如使用AnimatedBuilder - 如下面的回答

标签: flutter


【解决方案1】:
class ChangeRaisedButtonColor extends StatefulWidget {
  @override
  ChangeRaisedButtonColorState createState() => ChangeRaisedButtonColorState();
}

class ChangeRaisedButtonColorState extends State<ChangeRaisedButtonColor>
    with SingleTickerProviderStateMixin {
  AnimationController _animationController;
  Animation _colorTween;

  @override
  void initState() {
    _animationController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 300));
    _colorTween = ColorTween(begin: Colors.red, end: Colors.green)
        .animate(_animationController);

    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _colorTween,
      builder: (context, child) => RaisedButton(
            child: Text("Change my color"),
            color: _colorTween.value,
            onPressed: () {
              if (_animationController.status == AnimationStatus.completed) {
                _animationController.reverse();
              } else {
                _animationController.forward();
              }
            },
          ),
    );
  }
}

【讨论】:

  • 感谢您的回答! :) 注意:super.dispose(); 应该是 dispose 方法覆盖的最后一行。
【解决方案2】:

您可以使用 AnimatedContainer 作为 raiseButton child 。当颜色改变时,它会变成动画!

RaisedButton(
        onPressed: null,
        padding: EdgeInsets.all(0),
        child: AnimatedContainer(
          color: pageIndex == 1 ? Color(0xFF4B4B4B) : Color(0xFFD8D8D8),
          duration: Duration(milliseconds: 300),
        ),
      )

它只是一个容器,所以它可以有子文本..

【讨论】:

  • 您的(被低估和不受欢迎的)答案证明了使用 Flutter 编码变得多么容易!
  • 非常感谢!这正是我所需要的,而且效果很好。感谢您的回答,我什至不必尝试其他更复杂的答案。
  • @Andrey Turkovsky 的上述答案更好。例如,使用此方法的一个缺点是在点击时会丢失按钮的飞溅效果。
猜你喜欢
  • 2020-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 2014-10-20
  • 2015-05-18
  • 2017-01-21
  • 1970-01-01
相关资源
最近更新 更多