Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use showDialog with await

I have three examples of showDialog. I presume that _showAlert1 is correct, however it uses 2 functions to achieve it. _showAlert2 also works, however I presume it is not correct because I believe that showDialog is async, and I presume that this function relies on the dialog being displayed in sufficient time. _showAlert3 does not work because the dialog stays on the screen and does not clear.

If _showAlert2 although it works is incorrect for the above reason, could someone please show me how this should be structured so that this can be done in one function.

Examples:

void _showAlert0(BuildContext context, String text, int seconds) async {
    return await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            ));
  }

  void _showAlert1(BuildContext context, String text, int seconds) async {
    _showAlert0(context, text, seconds);
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
  }

  void _showAlert2(BuildContext context, String text, int seconds) async {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            ));
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
  }

void _showAlert3(BuildContext context, String text, int seconds) async {
    await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            ));
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
}
like image 363
Brian Oh Avatar asked Oct 11 '25 17:10

Brian Oh


1 Answers

Not sure if there is a better way, but the following appears to work. Note the "then" clause on the call to showDialog().

void _showAlert3(BuildContext context, String text, int seconds) async {
    showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) => AlertDialog(
              title: Text("Error"),
              content: Text(text),
            )).then((val) {});
    await Future.delayed(Duration(seconds: seconds));
    Navigator.of(context).pop(true);
  }

As for trolls, RTFQ ("structured so that this can be done in one function") and if you don't want to help then go away.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!