How to get AlertDialog Callback from method in Flutter?
Asked Answered
C

3

10

I have AlertDialog in static method, in that I wants to get callback when user clicks on OK button.

I tried using typedef but can't understand.

Below is My Code:

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
              },
            ),
          ],
        );
      },
    );
  }
}
Cockade answered 1/8, 2019 at 10:2 Comment(0)
N
18

You can simply wait for the dialog to be dismissed {returns null} or closed by clicking OK which, in this case, will 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
              },
            ),
          ],
        );
      },
    );
  }
}

And then when you call displayDialogOKCallBack you should await for the result

Example:

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

  if (result) {
   // Ok button is clicked
  }
}
Niela answered 1/8, 2019 at 10:24 Comment(3)
I think you mean if (result == true) { // Ok button is clicked } true instead of false in the condition to signify the ok button click.Arevalo
Is there a way to prevent the dialog from closing? I have a form in a dialog, and I need to keep the dialog open if there are errors.Lupus
Nevermind, I found a solution like what I was talking about and added it as an answer.Lupus
H
1

Then Callback function for Future work:

  DialogUtils.displayDialogOKCallBack().then((value) {
  if (value) {
   // Do stuff here when ok button is pressed and dialog is dismissed. 
  }
});
Hutment answered 14/6, 2020 at 13:20 Comment(0)
L
0

This thread is a bit old, but I found a solution that wasn't touched upon, so I thought I'd add it here.

I had a form in my AlertDialog, and I needed to keep the dialog open if there were any errors. This solution worked for me.

final GlobalKey<FormState> formKey = GlobalKey<FormState>();

Future _showEditDialog(BuildContext context) {
  return showDialog(
    context: context,
    builder: (context) {
      return WillPopScope(
        onWillPop: () async {
          return formKey.currentState!.validate();
        },
        child: AlertDialog(
          title: const Text("Awesome AlertDialog"),
          content: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            child: Form(
              key: formKey,
              child: Column(
                children: [
                  TextFormField(
                    validator: (value) {
                      if (value!.isEmpty) return "Please Fill Out This Field";
                      return null;
                    },
                  ),
                ],
              ),
            ),
          ),
          actions: <Widget>[
            MaterialButton(
              child: const Text("Cancel"),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ],
        ),
      );
    },
  );
}

The important part is the WillPopScope that I wrapped the AlertDialog. I think this absorbs all the Navigator.pop() calls and passes them through the onWillPop parameter. This parameter is passed an async function which returns a Future. I just returned the validation check boolean, but in the real world there would also be a http request here too.

Remember to add a way for the user to cancel the form without triggering the form validation. I just added a cancel button that runs Navigator.pop().

Hope this helps, let me know if anyone has any questions.

Lupus answered 25/1, 2023 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.