Search code examples
functionfluttercallbackflutter-alertdialog

How to get AlertDialog Callback from method in Flutter?


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

Solution

  • 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
      }
    }