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

时间:2018-11-05 20:52:02

标签: animation flutter duration

我想按需更新计时器,但是我不确定如何执行此操作。我想在更改持续时间之前检查小部件更新时是否满足某些条件。到目前为止,我尝试使用“ 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);
      }
  }
//...
}

1 个答案:

答案 0 :(得分:1)

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

animationController.duration = Duration(milliseconds: _duration)