*** UPDATE ***
I have a problem. When I use a Timer in Flutter and cancel() it afterwards, but as soon the cancel method is triggered, nothing happens.
var counter = 0;
Timer.periodic(const Duration(milliseconds: 50), (timer) {
developer.log('Actual counter ' + counter.toString());
counter++;
if (counter == 5) {
developer.log('TIMER DONE');
timer.cancel();
}
});
developer.log('This comes afterwards');
Expected out put:
Actual counter 0
Actual counter 1
Actual counter 2
Actual counter 3
Actual counter 4
TIMER DONE
This comes afterwards
The Output:
Actual counter 0
Actual counter 1
Actual counter 2
Actual counter 3
Actual counter 4
TIMER DONE
normally I should see a message ‘this is afterwards’ in the console, but it seems that with the cancel the complete method will be canceled.
Many thanks in advance.
2
Answers
Update: perform operation end of timer.
You need to add logic inside if condition to perform operation.
Here is an widget example
I can’t see any increment on
counter
on current snippet. that’s whycounter
remains 0 and doesnt meet the condition to cancel the timer.Perhaps it will be
Here is a fully working example using a
Timer
When you
startTimer()
, here is the output