6

我有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
              },
            ),
          ],
        );
      },
    );
  }
}
4

2 回答 2

12

您可以简单地等待对话框被解除 {returns null} 或单击关闭OK,在这种情况下,将返回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
  }
}
于 2019-08-01T10:24:52.047 回答
0

然后回调函数用于未来的工作:

  DialogUtils.displayDialogOKCallBack().then((value) {
  if (value) {
   // Do stuff here when ok button is pressed and dialog is dismissed. 
  }
});
于 2020-06-14T13:20:03.250 回答