首页
Preview

对于异步操作对话框showDialog传入context无效问题

在说到WillPopScope组件的用法时,用到showDialog。当用户点击返回箭头时,弹出询问框,代码如下:

Future<bool?> _onBackPressed() async{
    return showDialog<bool>(
        context: context,
        builder: (BuildContext context){
          return  AlertDialog(
            title: const Text('确定要退出吗?'),
            actions: [
              TextButton(
                  onPressed: (){
                    Navigator.of(context).pop(false);
                  },
                  child: const Text('取消')
              ),
              TextButton(
                  onPressed: (){
                    Navigator.of(context).pop(true);
                  },
                  child: const Text('确定')
              )
            ],
          );
        }
    );
  }
@override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        bool? result = await _onBackPressed();
        result ??= false; //判断是否为null,是就赋值false
        return result;
      },
      child: Scaffold(...)
       
    );
  }
  • 报错:
Undefined name 'context'
  • 原因: 生成Dialog的方法是在Widget类之外定义的,所以Widget类的context不存在。
  • 解决,传递一个context给_onBackPressed
Future<bool?> _onBackPressed(BuildContext context) async{}

调用的时候加一个context参数

_onBackPressed(context)

版权声明:本文内容由TeHub注册用户自发贡献,版权归原作者所有,TeHub社区不拥有其著作权,亦不承担相应法律责任。 如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

点赞(0)
收藏(0)
特困程序员
暂无描述

评论(0)

添加评论