Reputation: 11999
In a StatefulWidget, I implemented a deactivate()
method, which does some cleanup.
Actually, the StatefulWidget periodically polls a service and reloads itself with newly received data. Therefore, it uses a Timer()
, which periodically calls the server polling callback.
The deactivate()
gets called just fine. But at some deactivations of the widget, the asynchronous Timer()
still fires a last event and calls the callback - while the widget is partly deactivated.
This is my deactivate():
@protected
@mustCallSuper
void deactivate() {
// allow callback of Timeer() to not execute
_timerCanceled = true;
// Cancel the periodic Timer()
_timer.cancel();
// Should be called LAST or FIRST?
super.deactivate();
}
Q:General question: How to cancel some asynchronous Timer()
and ensure, that it doesn't any longer calls the provided callback.
Or: How to write code that cancels a Timer()
and execute code after a complete cancel operation, so that the callback of the Timer()
definitely won't get called.
Upvotes: 4
Views: 7687
Reputation: 8614
In the Flutter gallery application example, they use override dispose
in their State
class:
@override
void dispose() {
_timeDilationTimer?.cancel();
super.dispose();
}
I am not confident that is correct to create the Timer
inside the StatefulWidget
. You might want to refer to the gallery example (and other examples in the Flutter repository).
Upvotes: 10