天天看點

《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)