Reputation: 5
So I have created a timer that I can start and stop with a button. Mostly works fine, however if I spam the button to start and stop it really fast, it seems to start multiple timers at once and as a result, the function gets fired a lot faster than one second. Is there anyway that I can keep it at one timer at a time or some sort of way to cancel all the timers at once (I am very new to flutter and timers).
to start the timer:
void startTimer() {
Timer.periodic(Duration(seconds: seconds), (t) {
setState(() {
timer = t;
randomNote = Random().nextInt(6);
randomType = Random().nextInt(6);
});
});
}
to stop the timer:
timer?.cancel();
I have tried adding an if statement to check if a timer is active so the code looks like this:
void startTimer() {
if (timer?.isActive != true) {
Timer.periodic(Duration(seconds: seconds), (t) {
setState(() {
timer = t;
randomNote = Random().nextInt(6);
randomType = Random().nextInt(6);
})
});
}
}
But nothing changes.
Upvotes: 0
Views: 1205
Reputation: 1216
Well since you say if (timer?.isActive != true)
isn't working, an alternative to that is this,
bool isTimerOn = false;
...
void startTimer() {
if(!isTimerOn){
isTimerOn = true;
Timer.periodic(Duration(seconds: seconds), (t) {
setState(() {
timer = t;
randomNote = Random().nextInt(6);
randomType = Random().nextInt(6);
});
});
}
}
And if you're going to do timer?.cancel();
make sure to set isTimerOn
as false.
Upvotes: 0