flutter Unhandled Exception: setState() called after dispose()

在Flutter应用中,如果在页面卸载后尝试调用setState(),会出现‘setState() called after dispose()’的错误。避免这种错误的方法包括设置一个已卸载标记或检查mounted属性。在dispose()时取消定时器或停止监听,确保在调用setState()前检查mounted为true,可以有效防止此类错误并避免潜在的内存泄漏问题。
摘要由CSDN通过智能技术生成

涉及到页面在网络请求响应或者演示操作中,调用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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值