Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.

一、具體錯誤:

E/flutter ( 2631): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.

E/flutter ( 2631): At this point the state of the widget's element tree is no longer stable.

E/flutter ( 2631): To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

 

二、描述

項目中在主界面發起彈窗,然後在回調函數中又發起等待彈窗。等待彈窗的context繼承自第一個彈窗。當第一個彈窗

 Navigator.pop(context);之後,他的context不可用。所以當對等待彈窗調用context的時候,會報這個出錯。

                            showDialog(
                                  context: context,
                                  barrierDismissible: true,
                                  builder: (context) {
                                    return BackupDialog(
                                      sure: (type) {
                                        model.backup(type, context);
                                      },
                                    );
                                  },
                                ),    

tip:注意BackDialog的回調方法sure,其中的backup方法傳的是自身的context。將其改爲父context即可。如下

                                showDialog(
                                  context: context,
                                  barrierDismissible: true,
                                  builder: (_) {
                                    return BackupDialog(
                                      sure: (type) {
                                        model.backup(type, context);
                                      },
                                    );
                                  },
                                ),

三、總結

當出現該問題的時候,是由於context已經被銷燬,變得不可用。請檢測後面執行的代碼是否依賴了銷燬的context。

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