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屬性:在這裏插入圖片描述
由上圖可以看出來這個屬性在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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章