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

时间:2019-08-01 10:02:34

标签: function flutter callback flutter-alertdialog

我在静态方法中有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
              },
            ),
          ],
        );
      },
    );
  }
}

2 个答案:

答案 0 :(得分:2)

您只需单击OK即可等待对话框被关闭{returns null}或关闭,在这种情况下,该对话框将返回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 == false) {
   // Ok button is clicked
  }
}

答案 1 :(得分:0)

然后为将来的工作提供回调功能:

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