the error is thrown in two areas (and the app freezes (when the app is minimized, when phones back button is clicked, or when another app runs on top of the flutter app. Flu
You can use:
if (this.mounted) { // check whether the state object is in tree
setState(() {
// make changes here
});
}
The mounted
checks whether Whether this State
object is currently in a tree
.
mounted class
After an await
, your widget may not be mounted anymore. Doing setState gives you an exception at that time. This is actually a good thing, the code that follows should not be executing anyway, since you are somewhere else.
You have three options about the "setState() called after dispose()" exception:
if (!mounted) return;
between each await
and setState()
. It may be a good habit to put it after each await
.setState()
calls with setStateIfMounted()
and define it as:void setStateIfMounted(f) {
if (mounted) setState(f);
}
I explain the third approach in this video.