How to animate the color of a RaisedButton in Flutter?

后端 未结 2 812
我在风中等你
我在风中等你 2021-02-13 16:40

I have a RaisedButton. I want to animate it\'s color from green to red, and vice versa, every time the user click

相关标签:
2条回答
  • 2021-02-13 17:12

    You can use AnimatedContainer as raiseButton child . and when color changed it will be animated!

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

    and its just a container so it can have child like text..

    0 讨论(0)
  • 2021-02-13 17:20
    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();
                  }
                },
              ),
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题