i am trying to make it so that when the timer finishes, it automatically restarts but it seems i am running into some problems. here is the code
int _start = 7;
int? selectedValue;
void startTimer() {
const oneSec = Duration(seconds: 1);
_timer = Timer.periodic(
oneSec,
(Timer timer) {
if (_start == 0) {
setState(() {});
} else {
setState(() {
_start--;
});
}
},
);
}
void restartTimer() {
if (_timer != null) {
_timer.cancel();
}
setState(() {
_start = 5;
});
startTimer();
}
@override
void initState() {
// TODO: implement initState
startTimer();
restartTimer();
i would appreciate a fix to this problem
3
Answers
you need to call
restartTimer()
after the timer reaches zeroI would also suggest allowing zero and restarting after
If you could send the whole snippet it may be easier to see what is wrong but from what I can already see, you put the restart timer method in the initState, which means, the method will be called only once and at the wrong time.
What I would suggest is:
Here I took away the restart timer method and put it inside your start method where you check if the countdown is 0 or not.
Don’t forget to not put the int _start = 7 into the build, else when you will set the state again, the "start" will be 7 instead of 5 as you intended in your method (and the _start– won’t work either).
Hope it helped.
Change this way,
and