我希望能够按需更新计时器,但我不确定该如何操作。我想在小部件更新时检查是否满足特定条件,然后再更改持续时间。到目前为止,我已经尝试使用“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);
}
}
//...
}
if (controller.isAnimating) controller.forward();
以便动画速度基于新的持续时间而改变。查看AnimationController
代码的一瞥就会发现原因:内部参数在启动动画时而不是在设置 Duration 时更新。 - spenster