天天看点

flutter 报错 setState() called after dispose() This error happens if you call setState()。。。

在使用flutter做开发的时候 观察Console的时候发现的一个错误

先看一下这个错误的描述:

[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: setState() called after dispose():
 _HomeFunctionState#92aa2(lifecycle state: defunct, not mounted)
           

大致意思就是在dispose的时候调用了setSate()

详细的错误信息:

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.
           

大致意思就是一个组件已经不再出现了,但是你有调用了setState()方法。

这句话的后面也给出了相应的解决方案(两种):1.在dispose回调的方法中设置一个监听器来关闭计时器

2.在使用setState()方法前检测“mounted”属性是否还在组件树中

到这里已经大概知道怎么回事了,明白大概该怎么去解决bug。

看一下这个mounted属性:

flutter 报错 setState() called after dispose() This error happens if you call setState()。。。

由上图可以看出来这个属性在framework.dart里面,也有相应的解释:Whether this [State] object is currently in a tree.(是否state还在组件树中),最后一句话:It is an error to call [setState] unless [mounted] is true.(除非在mounted为true的时候调用setState(),否则 error)

到这里已经很明显了!

简单的解决方法大概就是:

if(mounted){
	setState((){
	//TODO:XXXXXXX
	});
}
           

方案二:设置监听器

参考:https://www.jianshu.com/p/d1c98b49ab43