【问题标题】:How to get AlertDialog Callback from method in Flutter?如何从 Flutter 中的方法获取 AlertDialog 回调?
【发布时间】:2019-12-09 21:42:32
【问题描述】:

我在静态方法中有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】:

    您可以通过点击OK 来等待对话框被关闭{返回 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) {
       // Ok button is clicked
      }
    }
    

    【讨论】:

    • 我想你的意思是 if (result == true) { // Ok button is clicked } true 而不是 false 表示点击ok按钮。
    【解决方案2】:

    然后为Future工作回调函数:

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

    【讨论】:

      猜你喜欢
      • 2021-08-26
      • 2021-12-07
      • 2016-03-27
      • 2020-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多