[flutter] 动态改变动画的值

376 阅读1分钟

# What would be the proper way to update animation values in a Flutter animation?

Tween可以复用动态改变动画值 我之前不知道!!!

知道这点 代码就很好写了

重置的时候先重置Tween的起始值,再重置AnimationController

否则Animation初始值会很奇怪

class _RoulettePageWidgetState extends State<RoulettePageWidget>
with SingleTickerProviderStateMixin {
   Animation<double> _animation;
   Tween<double> _tween;
   AnimationController _animationController;
   math.Random _random = math.Random();

   int position = 0;

   double getRandomAngle() {
      return math.pi * 2 / 25 * _random.nextInt(25);
   }

   @override
   void initState() {
      super.initState();
      _animationController =
          AnimationController(duration: Duration(seconds: 2), vsync: this);
      _tween = Tween(begin: 0.0, end: getRandomAngle());
      _animation = _tween.animate(_animationController)
          ..addListener(() {
              setState(() {});
          });
   }

   void setNewPosition() {
      _tween.begin = _tween.end; /// 先设置起始值
      _animationController.reset(); /// 再重置animationController
      _tween.end = getRandomAngle();
      _animationController.forward();
   }

   @override
   Widget build(BuildContext context) {
      return Container(
         child: Column(
            children: <Widget>[
               Center(
                  child: Transform.rotate(
                     angle: _animation.value,
                     child: Icon(
                        Icons.arrow_upward,
                     size: 250.0,
                  ),
               )),
               Expanded(
                  child: Container(),
               ),
               RaisedButton(
                  child: Text('SPIN'),
                  onPressed: setNewPosition,
               )
            ],
         )
      );
   }
}