天天看點

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