一尘不染

如何在Flutter中为RaisedButton的颜色设置动画?

flutter

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

如何做到这一点?


阅读 336

收藏
2020-08-13

共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();
              }
            },
          ),
    );
  }
}
2020-08-13