Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dispose to prevent memory leak

Tags:

flutter

dart

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?

like image 944
Michael Avatar asked May 31 '19 12:05

Michael


People also ask

How would you prevent a memory leak?

To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.

Does garbage collection prevent memory leaks?

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.

Which tool is used for memory leak?

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.


1 Answers

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.
    }
    // ...
  });
}
like image 200
George Avatar answered Oct 11 '22 13:10

George