Flutter常見問題 – setState() called after dispose()

使用Flutter過程中你可能會遇到這個Error

E/flutter ( 6468): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: setState() called after dispose(): HomePageState#2dd27(lifecycle state: defunct, not mounted)
E/flutter ( 6468): 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 ( 6468): 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 ( 6468): 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() 在dispose()之後調用而造成內存洩漏的錯誤,訊息中也有提供解決辦法。

中斷對象的引用

The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback.

以計數器為例

Timer _countdownTimer;

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    super.dispose();
  }

二、檢查對象是否存在

“mounted” property of this object before calling setState() to ensure the object is still in the tree.

mounted 這個屬性是為你判斷此物件當前是否還存在於樹中,因此你只需要在setState外加一句判斷。

if(mounted){
        setState(() {
		..
	})
}

if (!mounted) return;

setState(){
    /** **/
}

API : https://api.flutter.dev/flutter/widgets/State/mounted.html

4e52d54f6bc42abb41d26eb5b0df6517?s=250&d=wavatar&r=g Flutter常見問題 - setState() called after dispose()
0 0 評分數
Article Rating
訂閱
通知
guest
0 Comments
在線反饋
查看所有評論