天天看点

《Flutterl实战》例子showDialog报错Undefined name 'context'.

控件代码如下:

//点击该按钮后弹出对话框
RaisedButton(
  child: Text("对话框1"),
  onPressed: () async {
    //弹出对话框并等待其关闭
    bool delete = await showDeleteConfirmDialog1();
    if (delete == null) {
      print("取消删除");
    } else {
      print("已确认删除");
      //... 删除文件
    }
  },
),

// 弹出对话框
Future<bool> showDeleteConfirmDialog1() {
  return showDialog<bool>(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: Text("提示"),
        content: Text("您确定要删除当前文件吗?"),
        actions: <Widget>[
          FlatButton(
            child: Text("取消"),
            onPressed: () => Navigator.of(context).pop(), // 关闭对话框
          ),
          FlatButton(
            child: Text("删除"),
            onPressed: () {
              //关闭对话框并返回true
              Navigator.of(context).pop(true);
            },
          ),
        ],
      );
    },
  );
}
           

报错

Undefined name 'context'.
           

报错原因:

生成Dialog的方法是在Widget类之外定义的,所以Widget类的

context

不存在。

解决方法:

传递一个context给showDialog

Future<bool> showDeleteConfirmDialog1(BuildContext context) {
    …………
}
           

调用的时传入context:

showDeleteConfirmDialog1(context)