如何在didUpdateWidget中更改Flutter动画的持续时间?

12

我希望能够按需更新计时器,但我不确定该如何操作。我想在小部件更新时检查是否满足特定条件,然后再更改持续时间。到目前为止,我已经尝试使用“didUpdateWidget”函数进行调试,但是我遇到了单个ticker错误。当我将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);
      }
  }
//...
}
1个回答

20

经过仔细查看文档后,我意识到你可以直接更改AnimationController的属性。哈哈...

animationController.duration = Duration(milliseconds: _duration)

10
给其他查找此问题的人一个建议:如果你希望在动画控制器运行时更新持续时间更改(即实时更新),那么似乎你必须再次激活动画运动。换句话说,在我的情况下,更新 Duration 后,我必须添加 if (controller.isAnimating) controller.forward(); 以便动画速度基于新的持续时间而改变。查看 AnimationController 代码的一瞥就会发现原因:内部参数在启动动画时而不是在设置 Duration 时更新。 - spenster
我必须在我的代码中添加 controller.repeat()。 - MobileMon
2
你们救了我!非常感谢! - 임세준

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接