Flutter error: setState() called after dispose()

Updated: January 25, 2023 By: Hadrianus 8 comments

This article is about a common error that you might encounter when building apps with Flutter.

The Problem

When working with Flutter, you may face this error:

Unhandled Exception: setState() called after dispose()

More information:

Lifecycle state: defunct, not mounted)

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().

Solutions

You may notice that not only one but two solutions are mentioned in the error message.

The first solution is to cancel the timer or stop listening to the animation in the dispose() callback.

The second solution is to check the mounted property of the state class of your widget before calling setState(), like this:

if (!mounted) return;

setState(){
    /* ... */
}

Or:

if (mounted) {
  setState(() {
    /* ... */
  });
}

Hope this helps.

Conclusion

You’ve learned how to solve the setState() called after dispose() error in Flutter. Keep the ball rolling and continue exploring more intersting stuff about Flutter by taking a look a the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
8 Comments
Inline Feedbacks
View all comments
Nishant
Nishant
2 years ago

thanks

Dhan
Dhan
2 years ago

It’s works for me, thanks a lot

Jessica
Jessica
2 years ago

wow thanks a lot

Achini Amandila
Achini Amandila
2 years ago

It helped me thank you so much brother!

Shrey
Shrey
2 years ago

Thanks a lot.

Atharv
Atharv
2 years ago

thank you

,iuz
,iuz
3 years ago

Thank you!

Isaiah
Isaiah
3 years ago

It helped me thank you brother!

Related Articles