I've this init state method:
@override
void initState() {
super.initState();
getNumber(index).then((number) {
if (number> 1000) {
number = number/ 1000;
setState(() {
flag = true;
_num = number.toInt().toString();
});
} else {
setState(() {
_num = number.toInt().toString();
});
}
});
}
And i got this error:
This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback. The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
How i use dispose in the right way?
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
Although garbage collection prevents many types of memory leaks, it doesn't prevent all of them. In automatic reference counting systems, such as Perl or Objective-C, memory is leaked whenever there are cyclical references, since the reference count is never decremented to zero.
Memory profilers are tools that can monitor memory usage and help detect memory leaks in an application. Profilers can also help with analyzing how resources are allocated within an application, for example how much memory and CPU time is being used by each method.
I can't account for this being a standard, but in my code I usually check for mounted
in every Future
event; whether it's .then
, .catchError
, or .whenComplete
callbacks.
@override
void initState() {
super.initState();
getNumber(index).then((number) {
if (!mounted) {
return; // Just do nothing if the widget is disposed.
}
// ...
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With