【问题标题】:How do you change the duration of a flutter animation on didUpdateWidget?你如何改变 didUpdateWidget 上颤动动画的持续时间?
【发布时间】:2019-04-09 06:19:31
【问题描述】:

我想根据需要更新计时器,但我不知道该怎么做。我想在更改持续时间之前检查更新小部件时是否满足某些条件。到目前为止,我已经尝试过使用“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);
      }
  }
//...
}

【问题讨论】:

    标签: animation flutter duration


    【解决方案1】:

    我发现,仔细查看文档后,您可以直接更改 AnimationController 的属性。哈哈...

    animationController.duration = Duration(milliseconds: _duration)
    

    【讨论】:

    • 只是对查看此内容的其他人的评论:如果您希望动态更新持续时间更改(即,在动画控制器运行时),那么您似乎必须激活动画再次运动。换句话说,就我而言,在更新持续时间后,我必须添加if (controller.isAnimating) controller.forward(); 以使动画的速度根据新的持续时间发生变化。查看AnimationController 代码说明了原因:内部参数不是在设置持续时间时更新,而是在启动动画时更新。
    • 我必须添加 controller.repeat() 到我的
    • 你们救了我!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2021-01-17
    • 2019-08-28
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    相关资源
    最近更新 更多