首页 > 解决方案 > Flutter 按顺序删除对话框

问题描述

我正在尝试按特定顺序删除对话框,但出现以下错误:

E/flutter (14457): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: Unhandled exception:
E/flutter (14457): Looking up a deactivated widget's ancestor is unsafe.
E/flutter (14457): At this point the state of the widget's element tree is no longer stable. To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling inheritFromWidgetOfExactType() in the widget's didChangeDependencies() method.

这里的顺序:

  1. 项目清单
  2. 打开确认对话框 1
  3. 关闭 (onPressed) 对话框 1
  4. 打开加载对话框 2。
  5. 关闭 (Navigator.of(context).pop())
  6. 打开对话框 3 并显示成功消息。

Dialog 1 和 2 都使用 Navigator.of(context).pop() 关闭。

我怎样才能解决这个问题?

标签: flutter

解决方案


使用该功能Navigator.of(context).pop()时,不要使用上一个对话框的上下文,尝试使用页面的上下文。原因Looking up a deactivated widget's ancestor is unsafe是上一个对话框已关闭,但您使用了该对话框的上下文。您可以查看源代码:

static NavigatorState of(
    BuildContext context, {
      bool rootNavigator = false,
      bool nullOk = false,
    }) {
    final NavigatorState navigator = rootNavigator
        ? context.rootAncestorStateOfType(const TypeMatcher<NavigatorState>())
        : context.ancestorStateOfType(const TypeMatcher<NavigatorState>());// here check the ancestor state,and throw the error
    assert(() {
      if (navigator == null && !nullOk) {
        throw FlutterError(
          'Navigator operation requested with a context that does not include a Navigator.\n'
          'The context used to push or pop routes from the Navigator must be that of a '
          'widget that is a descendant of a Navigator widget.'
        );
      }
      return true;
    }());
    return navigator;
  }

推荐阅读