riki
riki

Reputation: 1715

call setState() on a State object for a widget

The code below flutter deals with the management of a bottombar when the code is executed, click on the Icons.add button and then change bottom element the system displays following error:

Error:

[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _HomeViewScreenState#d0762(lifecycle state: defunct, tickers: tracking 1 ticker)

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

Flutter Code

Flutter Code HomeState

Upvotes: 2

Views: 2314

Answers (1)

Alex Usmanov
Alex Usmanov

Reputation: 158

You need to check if the widget is mounted. Instead of calling setState directly, use:

if (mounted)
    setState(() {});

Explanation: When you navigate away from the screen, widget gets disposed. So you cannot call setState() on it

Upvotes: 5

Related Questions