【问题标题】:Flutter Looking up a deactivated widget's ancestor on dialog popFlutter 在对话框弹出时查找已停用的小部件的祖先
【发布时间】:2022-11-12 00:25:15
【问题描述】:

我在尝试弹出包含圆形加载器的对话框时遇到问题。一旦我的数据被加载,我实际上弹出很好,但在调试模式下它显示一个我无法弄清楚如何修复的异常。

我有一个有状态的屏幕,在初始化时我使用以下代码:

WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  showLoading();
});

方法showLoading如下:

void showLoading() {
  //let's show the loading bar
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      dialogContext = context;
      return AppLoader();
    },
  );
}

AppLoader 简单返回的地方:

class AppLoader extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Center(
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            SizedBox(
              child: new CircularProgressIndicator(),
              height: 80.0,
              width: 80.0,
            ),
          ],
        ),
      ),
    );
  }
}

dialogContent 在类的初始定义为:

late BuildContext dialogcontext;

我的代码的主要部分如下所示:

@override
Widget build(BuildContext context) {
  return Container(
    color: ColorConstant.gray100,
    child: Scaffold(
      backgroundColor: ColorConstant.gray100,
      body: Stack(
        children: <Widget>[
          getMainListViewUI(),
          SizedBox(
            height: MediaQuery.of(context).padding.bottom,
          )
        ],
      ),
    ),
  );
}

Widget getMainListViewUI() {
  return FutureBuilder<bool>(
    future: getData(),
    builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          return ListView.builder(
          itemCount: listViews.length,
          scrollDirection: Axis.vertical,
          itemBuilder: (BuildContext context, int index) {
            return listViews[index];
          },
        );
    },
  );
}

基本上,我遇到的问题是,当我完成从 (getData()) 获取数据时,我使用:

Navigator.pop(dialogContext);

这很好用:它删除了圆形加载器,我可以看到它后面的屏幕,没有问题,没有错误。但是,如果我在调试模式下运行,当我进行热同步时,它总是向我显示错误: Looking up a deactivated widget's ancestor on dialog pop

我知道这是因为我正在使用 Navigator.pop,但我不明白。我已经定义了 dialogContext,这是我传递给 showDialog 的内容,这就是我要弹出的内容。我也尝试过设置一个预定的导航器,但同样的问题。

请问有什么建议吗?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    您可以检查小部件是否已安装。当您传递上下文并具有异步功能时,可能会出现此问题。你可以在导航之前添加这个,看看问题是否解决了

    if(!mounted) return;
    

    【讨论】:

    • 但是,如果挂载了小部件,您的意思是将 Navigator.pop 放在 if 语句中吗?如果是这样,我也试过了,不幸的是它没有用。
    • 不再像您在使用上下文之前放置此语句一样,因此如果未安装小部件,则导航将不起作用
    • 啊,明白了!好的,我会试一试并恢复。
    • 不幸的是,这并没有做任何事情。
    【解决方案2】:

    问题解决了。问题是我的 getData 方法被多次调用,第一次很好地弹出加载小部件,之后它会抛出正确的错误,因为加载小部件不再存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 2021-06-03
      • 2021-07-28
      • 2021-04-29
      • 1970-01-01
      • 2020-06-19
      • 2020-09-18
      • 2021-11-15
      相关资源
      最近更新 更多