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

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

错误原因

flutter端请求网络时,调用的是宿主App的网络请求。

flutter通过消息通道发送一个消息,然后await等待消息返回,最终宿主app会调用reply.reply(obj)方法返回数据。如果在这个过程中,flutter页面关闭,就会出现如下异常,类似Android中的内存泄漏。

2019-04-29 14:01:43.593 10294-10635/com.tinytongtong.flutter E/flutter: [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: setState() called after dispose(): _SystemMessageListRouteState#017f6(lifecycle state: defunct, not mounted)
    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. 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.
    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().
解决方式

上面的日志说的很明白。

我们的错误原因是异步消息未返回,所以在setState方法之前调用mouted属性进行判断即可。具体示例如下:

      if(mounted){
        setState(() {
          _listData.addAll(list);
      }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tinyvampirepudge

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值