您如何更改 didUpdateWidget 上颤动动画的持续时间?

Joh*_*Boy 8 animation duration flutter

我想按需更新计时器,但我不知道如何去做。我想检查在更改持续时间之前更新小部件时是否满足某些条件。到目前为止,我已经尝试使用“didUpdateWidget”函数,但我收到了一个代码错误。当我将 mixin 更改为 TickerProviderStateMixin 时,持续时间不会更新。

class _ProgressBarState extends State<ProgressBar>
    with SingleTickerProviderStateMixin {

  int _duration;
  int _position;
  bool _isPaused;

  Animation animation;
  AnimationController animationController;

  @override
  void initState() {
    super.initState();
    _duration = widget.duration;
    _position = widget.position;
    _isPaused = widget.isPaused;
    animationController = AnimationController(
    duration: Duration(milliseconds: _duration), vsync: this);
    animation = Tween(begin: 0.0, end: 1.0).animate(animationController);
  }

  @override
    void didUpdateWidget(ProgressBar oldWidget) {
      // TODO: implement didUpdateWidget
      setState(() {
        _duration = widget.duration;
        _position = widget.position;
        _isPaused = widget.isPaused;
      });

      updateController(oldWidget);
      super.didUpdateWidget(oldWidget);
    }


  void updateController(ProgressBar oldWidget){
    if(oldWidget.duration != _duration){
      animationController.dispose();
      animationController = AnimationController(duration: Duration(milliseconds: _duration), vsync:this);
    }
    if(_isPaused){
      animationController.stop();
    } else{
        animationController.forward(from: _position/_duration);
      }
  }
//...
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*Boy 14

仔细看了文档,发现直接修改AnimationController的属性就可以了。哈哈...

animationController.duration = Duration(milliseconds: _duration)
Run Code Online (Sandbox Code Playgroud)

  • 只是对其他查找此内容的人的评论:如果您希望动态更新持续时间更改(即,在动画控制器运行时),那么似乎您必须再次激活动画运动。换句话说,就我而言,更新持续时间后,我必须添加“if (controller.isAnimating)controller.forward();”,以便动画的速度根据新的持续时间进行更改。查看“AnimationController”代码即可了解原因:内部参数不是在设置持续时间时更新,而是在启动动画时更新。 (7认同)
  • 你们救了我!多谢 ! (2认同)