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);
}
}
//...
}
_duration){ animationController. dispose(); animationController = AnimationController(duration: Duration(milliseconds: _duration), vsync:this); } if(_isPaused){ animationController. stop(); } else{ animationController. forward(from: _position/_duration); } } //... }
What is vsync ? Vsync basically keeps the track of screen, so that Flutter does not renders the animation when the screen is not being displayed.
Timer is unrelated to Flutter, and is just a timer like you'd fine in any other language. On the other hand, AnimationController (and Ticker , its equivalent of Timer ) is Flutter specific. The difference with a Timer is that, by using AnimationController , the "ticker" can be muted, slowed, or mocked.
All you need is Controller. reset() to stop the animation and Controller. repeat() to start it. However if you need to start the animation just once, use Controller.
I realized that after carefully looking at the documents, you could just change the properties of AnimationController directly. haha...
animationController.duration = Duration(milliseconds: _duration)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With