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

问题描述 投票:2回答:1

我在静态方法中有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
              },
            ),
          ],
        );
      },
    );
  }
}
function flutter callback flutter-alertdialog
1个回答
4
投票

您只需单击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
  }
}

0
投票

然后为将来的工作使用回调函数:

  DialogUtils.displayDialogOKCallBack().then((value) {
  if (value) {
   // Do stuff here when ok button is pressed and dialog is dismissed. 
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.