如何从 Flutter 中的方法获取 AlertDialog 回调?

How to get AlertDialog Callback from method in Flutter?

我在静态方法中有 AlertDialog,因为我想在用户单击 OK 按钮时获得回调。

我尝试使用 typedef 但无法理解。

下面是我的代码:

class DialogUtils{

  static void displayDialogOKCallBack(BuildContext context, String title,
      String message)
  {
    showDialog(
      context: context,
      builder: (BuildContext context) {
         return AlertDialog(
          title: new Text(title, style: normalPrimaryStyle,),
          content: new Text(message),
          actions: <Widget>[
            new FlatButton(
              child: new Text(LocaleUtils.getString(context, "ok"), style: normalPrimaryStyle,),
              onPressed: () {
                Navigator.of(context).pop();
                // HERE I WANTS TO ADD CALLBACK
              },
            ),
          ],
        );
      },
    );
  }
}

您只需等待对话框关闭 {returns null} 或通过单击 OK 关闭,在这种情况下,将 return true

class DialogUtils {
  static Future<bool> displayDialogOKCallBack(
      BuildContext context, String title, String message) async {
    return await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text(title, style: normalPrimaryStyle,),
          content:  Text(message),
          actions: <Widget>[
             FlatButton(
              child:  Text(LocaleUtils.getString(context, "ok"), style: normalPrimaryStyle,),
              onPressed: () {
                Navigator.of(context).pop(true);
                // true here means you clicked ok
              },
            ),
          ],
        );
      },
    );
  }
}

然后当您调用 displayDialogOKCallBack 时,您应该 await 得到结果

示例:

onTap: () async {
  var result =
  await DialogUtils.displayDialogOKCallBack();

  if (result) {
   // Ok button is clicked
  }
}

Then Callback function for Future work:

  DialogUtils.displayDialogOKCallBack().then((value) {
  if (value) {
   // Do stuff here when ok button is pressed and dialog is dismissed. 
  }
});