首页 文章

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

提问于
浏览
0

我有 RaisedButton . 每次用户点击它时,我想 animate 的颜色从 greenred ,反之亦然 .

怎么做到这一点?

1 回答

  • 2
    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
      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();
                  }
                },
              ),
        );
      }
    }
    

相关问题