flutter:报错之: Looking up a deactivated widget's ancestor is unsafe

本文分析了Flutter中一个常见错误“Looking up a deactivated widget's ancestor is unsafe”的原因,该错误通常发生在尝试访问无效上下文时。通过具体代码示例,详细解释了错误发生的情景,并提供了解决方案,即在调用函数时传递正确的BuildContext对象。

错误内容

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

我理解的错误原因

找不到靠谱的上下文,也就是我所传递的上下文无效了。

1.出现错误的地方

 void countdownAlertTime(BuildContext context) {
      print("进入倒计时");
    new Timer(new Duration(seconds: 2), () {
      print("进入倒计时回调中");
      Navigator.of(context).pop();  //就是这句出的问题
      print("第一次页面pop");
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
                title: new Text("恭喜"),
                content: new Text("操作成功!"),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  )
                ]);
          });
          setState(() {
        _alertTime = _tmpAlertTime;
      });
    });
  }

2.countdownAlertTime()在此处被调用

在这里插入图片描述

3.showInputDialog()在此处被调用

在这里插入图片描述

分析 纯自己理解

C =>B=>A
C被B调用,B被A调用,其中的context (BuildContext对象) 已经指代不明确了。就是报错的意思,上下文有丢失的意思。

解决方案。

在A调用时 传递 this.context 能正确指代 最初的context上下文。
在这里插入图片描述

结语

好了 继续去撸代码了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值