How do you change the duration of a flutter animation on didUpdateWidget?
5,823
I realized that after carefully looking at the documents, you could just change the properties of AnimationController directly. haha...
animationController.duration = Duration(milliseconds: _duration)
Author by
Johnny Boy
Updated on November 20, 2022Comments
-
Johnny Boy over 1 year
I want to have a timer updated on demand but I'm not sure how to go about doing this. I want to check that certain conditions are met when the widget is updated before changing the duration. So far, I've tried playing around with the "didUpdateWidget" function but I get an single ticker error. When I change the mixin to TickerProviderStateMixin, the duration doesn't update.
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); } } //... }
-
spenster almost 5 yearsJust a comment for others that look this up: if you want the duration change to be updated on the fly (i.e., while the animation controller is running), then it seems you have to activate the animation movement again. In other words, in my case, after updating the Duration, I had to add
if (controller.isAnimating) controller.forward();
in order for the speed on the animation to change based on the new duration. A peek at theAnimationController
code shows why: the internal parameters are updated not on setting the duration but on starting the animation. -
MobileMon about 3 yearsI had to add controller.repeat() to mine
-
임세준 over 2 yearsYou guys saved me! Thanks a lot !