Flutter setState() called after dispose()内存泄露解决

  • 发表于
  • flutter

Flutter中setState导致的内存泄漏——setState() called after dispose()


E/flutter (18151): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): MyPageState#630fa(lifecycle state: defunct, not mounted)

E/flutter (18151): 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.

E/flutter (18151): 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.

E/flutter (18151): 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 setState() called after dispose()内存泄露解决





只需在调用setState()之前检查您的窗口小部件的状态类 mounted 的属性。除非 mounted 为true,否则调用setState是错误的。

或者在 setState()之前写一行