flutter
lifecycle_error
ai_generated
true
setState() called after dispose(): _MyWidgetState#abcde(lifecycle state: defunct, not mounted)
ID: flutter/setstate-after-dispose
90%Fix Rate
90%Confidence
1Evidence
2023-11-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Flutter 3.16 | active | — | — | — |
| Dart 3.2 | active | — | — | — |
| Android SDK 33 | active | — | — | — |
| iOS 16 | active | — | — | — |
Root Cause
A stateful widget's setState() is invoked after the widget has been removed from the tree and disposed, often due to an asynchronous callback completing after disposal.
generic中文
有状态小部件的 setState() 在小部件已从树中移除并释放后被调用,通常是由于异步回调在释放后完成。
Official Documentation
https://api.flutter.dev/flutter/widgets/State/setState.htmlWorkarounds
-
95% success Check the 'mounted' property before calling setState() in asynchronous code.
Check the 'mounted' property before calling setState() in asynchronous code.
-
85% success Cancel subscriptions or futures in the dispose() method to prevent callbacks from firing.
Cancel subscriptions or futures in the dispose() method to prevent callbacks from firing.
-
70% success Use a StatefulWidget with AutomaticKeepAliveClientMixin if the widget should persist across navigation.
Use a StatefulWidget with AutomaticKeepAliveClientMixin if the widget should persist across navigation.
中文步骤
在异步代码中调用 setState() 前检查 'mounted' 属性。
在 dispose() 方法中取消订阅或 future,以防止回调触发。
如果小部件应在导航中保持存活,使用带有 AutomaticKeepAliveClientMixin 的 StatefulWidget。
Dead Ends
Common approaches that don't work:
-
Calling setState() in a try-catch block and ignoring the error
80% fail
Does not prevent the call; the error still occurs and may cause undefined behavior.
-
Wrapping setState() in a timeout to delay execution
60% fail
Delay does not guarantee the widget is still mounted; race condition remains.
-
Using a global flag to skip setState() without checking mounted
50% fail
Global flags are error-prone and may miss widget-specific lifecycle states.