FlutterError (setState() called after dispose(): (lifecycle state: defunct, not mounted)

后端 未结 2 917
别跟我提以往
别跟我提以往 2020-12-21 22:56

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

相关标签:
2条回答
  • 2020-12-21 23:03

    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

    0 讨论(0)
  • 2020-12-21 23:11

    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:

    1. Safely ignore it. The exception is saving your function from continuing.
    2. Place a if (!mounted) return; between each await and setState(). It may be a good habit to put it after each await.
    3. Replace your setState() calls with setStateIfMounted() and define it as:
    void setStateIfMounted(f) {
      if (mounted) setState(f);
    }
    

    I explain the third approach in this video.

    0 讨论(0)
提交回复
热议问题