涉及到页面在网络请求响应或者演示操作中,调用setState方法的,可能会出现setState() called after dispose()
的错误提示。
解决方法1:
其规避方法是制作一个记录页面是否退出的bool alreadyDispose标记,在页面退出时设置该标志为真。
这样当随后有操作要调用setState时,只有alreadyDispose为false才调用即可。
解决方法2:
flutter sdk的官方文档中提供了如下方式,即分析mounted标志,只有mounted为true才执行setState操作
/// Whether this [State] object is currently in a tree.
///
/// After creating a [State] object and before calling [initState], the
/// framework "mounts" the [State] object by associating it with a
/// [BuildContext]. The [State] object remains mounted until the framework
/// calls [dispose], after which time the framework will never ask the [State]
/// object to [build] again.
///
/// It is an error to call [setState] unless [mounted] is true.
bool get mounted => _element != null;
详细错误内容:
E/flutter ( 5585): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: setState() called after dispose(): _UserAddressListPageState#e3aeb(lifecycle state: defunct, not mounted)
E/flutter ( 5585): 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 ( 5585): 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 ( 5585): 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().
E/flutter ( 5585): #0 State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1197:9)
E/flutter ( 5585): #1 State.setState (package:flutter/src/widgets/framework.dart:1232:6)