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

3 Answers 3

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
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean if (result == true) { // Ok button is clicked } true instead of false in the condition to signify the ok button click.
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.
Nevermind, I found a solution like what I was talking about and added it as an answer.
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. 
  }
});

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.