0

I want to ask user "Yes" or "No", to continue (or not) some action. I have code that shows alert, but don't know how to close automatically alert dialog after user have clicked one of the two buttons.

bool showAlertDialog(BuildContext context, String message) {
  bool returnValue = false;
  // set up the buttons
  Widget cancelButton = ElevatedButton(
    child: Text("Cancel"),
    onPressed: () { returnValue = false; },
  );
  Widget continueButton = ElevatedButton(
    child: Text("Continue"),
    onPressed: () { returnValue = true; },
  ); // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("Do you want to continue?"),
    content: Text(message),
    actions: [
      cancelButton,
      continueButton,
    ],
  ); // show the dialog
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
  return returnValue;
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56

1 Answers1

1

A better way will be retuning bool on pop imo.

Future<bool> showAlertDialog(BuildContext context, String message) async {
  // set up the buttons
  Widget cancelButton = ElevatedButton(
    child: Text("Cancel"),
    onPressed: () {
      // returnValue = false;
      Navigator.of(context).pop(false);
    },
  );
  Widget continueButton = ElevatedButton(
    child: Text("Continue"),
    onPressed: () {
      // returnValue = true;
      Navigator.of(context).pop(true);
    },
  ); // set up the AlertDialog
  AlertDialog alert = AlertDialog(
    title: Text("Do you want to continue?"),
    content: Text(message),
    actions: [
      cancelButton,
      continueButton,
    ],
  ); // show the dialog
  final result = await showDialog<bool?>(
    context: context,
    builder: (BuildContext context) {
      return alert;
    },
  );
  return result ?? false;
}
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56