134

I am new to flutter, I want to dismiss my dialog after the task completion. I've tried with:

Navigator.pop(context, true); 

But my screen is getting black and dialog is still up there. here is my dialog code.

Dialog _dialog = new Dialog(
  child: new Row(
    mainAxisSize: MainAsixSize.min, 
    children: <Widget> [
    new CircularProgressIndicator(), 
    new Text("Loading")]),     

); 

14 Answers 14

167

https://api.flutter.dev/flutter/material/showDialog.html says

The dialog route created by this method is pushed to the root navigator. If the application has multiple Navigator objects, it may be necessary to call Navigator.of(context, rootNavigator: true).pop(result) to close the dialog rather just Navigator.pop(context, result).

so I'd assume one of these two should do what you want.

10
  • 8
    what is 'result' here?
    – Ammy Kang
    Jun 4, 2018 at 15:11
  • 7
    result is an optional argument that the route which called showDialog can receive. It's useful if for example your dialog select a value that the UI need to use. Jun 4, 2018 at 15:12
  • 2
    Any value you want the Future returned from showDialog() complete with when you dismiss the dialog. Jun 4, 2018 at 15:12
  • 1
    0.3.2 sounds a bit outdated. What is actually the current state. " its working for real device" and "also not working for android device" seem contradicting. Jun 4, 2018 at 15:30
  • 2
    working for iOS device, but not for android device and simulator, let me try to upgrade flutter. and Thanks a lot @GünterZöchbauer
    – Ammy Kang
    Jun 4, 2018 at 15:32
89

This code works for me:

  BuildContext dialogContext;
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      dialogContext = context;
      return Dialog(
        child: new Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            new CircularProgressIndicator(),
            new Text("Loading"),
          ],
        ),
      );
    },
  );

  await _longOperation();
  Navigator.pop(dialogContext);
7
  • 8
    this should be the accepted answer. Using the context that's not from the builder causes the screen to navigate pop instead of closing the dialog. Dec 28, 2020 at 1:56
  • 1
    Agreed to @AxesGrinds Jan 4, 2021 at 17:16
  • What happens here if the user press back button while the _longOperation is still in progress? Feb 14, 2021 at 16:14
  • Awesome, this helped me with an edge case where the dialog won't dismiss using a basic Navigator.of(context).pop(). Thanks!
    – Toma
    Apr 1, 2021 at 0:20
  • 1
    This didn't work for me with a popup inside a CupertinoTabScaffold. The screen below would be dismissed, but the popup would stay (and clicking again throws an exception that the widget has no root). A CupertinoTabScaffold has multiple navigator objects, while the dialog is pushed to the root navigator.
    – Harmen
    Jan 2, 2022 at 18:26
36

If you don't want to return any result after showDialog is closed, you can use

Navigator.pop(context);

If you want to pass result call

Navigator.pop(context, result);

Example:

showDialog(
    context: context,
    builder: (_) {
      return AlertDialog(
        title: Text('Wanna Exit?'),
        actions: [
          FlatButton(
            onPressed: () => Navigator.pop(context, false), // passing false
            child: Text('No'),
          ),
          FlatButton(
            onPressed: () => Navigator.pop(context, true), // passing true
            child: Text('Yes'),
          ),
        ],
      );
    }).then((exit) {
  if (exit == null) return;

  if (exit) {
    // user pressed Yes button
  } else {
    // user pressed No button
  }
});
22
//it work conrrectly
onPressed: () {
   Navigator.of(context, rootNavigator: true).pop();
},
0
14

Generally Navigator.pop(context); works.

But If the application has multiple Navigator objects and dialogBox doesn't close, then try this

Navigator.of(context, rootNavigator: true).pop();

If you want to pass result call, try

Navigator.pop(context,result);

OR

Navigator.of(context, rootNavigator: true).pop(result);

11

Better to use Completer, because if your operation is too short or the device is too slow, then the dialogContext variable will not be initialized and you can't close the dialog.

final dialogContextCompleter = Completer<BuildContext>();
showDialog<void>(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext dialogContext) {
    if(!dialogContextCompleter.isCompleted) {
      dialogContextCompleter.complete(dialogContext);
    }
    return AlertDialog(
      content: CircularProgressIndicator(),
    );
  },
);

// Close progress dialog
final dialogContext = await dialogContextCompleter.future;
Navigator.pop(dialogContext);
1
  • 1
    I think this should be the accepted answer. I had to detect whether multiple dialogs were opened and handle situations to only have single dialog opened. This was the only way to reliably close them. Oct 8, 2021 at 19:33
5

In 2023 here is the latest way to do that. Because in my case Navigator.of(context).pop(); didn't work

Navigator.of(context, rootNavigator: true).pop();
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Mar 22, 2023 at 19:59
4

This will close the dialog/alert box.

Navigator.of(context).pop();
2
showDialog(
  context: context,
  builder: (BuildContext context) => Center(
    child: CircularProgressIndicator(),
  ),
);

await Future<int>.delayed(Duration(seconds: 3));

Navigator.of(context, rootNavigator: true).pop();
2

Try this. It will definitely work. use the context of pageBuilder in Navigator to pop the dialog from screen.

showGeneralDialog(
     context: context,
     barrierLabel: "XYZ",
     barrierDismissible: true,
     barrierColor: Colors.black.withOpacity(0.7),
     pageBuilder: (dialogContext, __, ___) {
       return Center(
        child: Container(
          height: 240,
          margin: const EdgeInsets.symmetric(horizontal: 15),
          decoration: bd,
          child: SizedBox.expand(
              GestureDetector(
                   onTap: (){
                       Navigator.pop(dialogContext);
                    },
                    child: const Padding(
                       padding: EdgeInsets.fromLTRB(10,0,10,0),
                       child: Icon(Icons.close, size: 26, color:Colors.white),
                     ),
               ),
           )
         ) 
       );
     }
  );

 
2

You can use _dialogContext to handle closing the dialog, just you should check some conditions before calling pop() (_dialogContext != null && _dialogContext!.mounted).

    BuildContext? _dialogContext;    
    
    showDialog<void>(
                      context: context,
                      builder: (ctx) {
                        _dialogContext = ctx;
                        return AlertDialog(content: child);
                      },
                    );
    
    
    //close dialog
     if (_dialogContext != null && _dialogContext!.mounted) {
          Navigator.pop(_dialogContext!);
        }
1

Add on to Günter's answers. If you need to dismiss it when the user clicks elsewhere change this property to true

barrierDismissible: true,
1

Expanding on the answer from @live-long, you can create a class to handle the showing and dismissing of the dialog.

Example:

class ProcessingDialog {
  ProcessingDialog({
    required this.context,
    required this.child,
  });
  final BuildContext context;
  final Widget child;
  BuildContext? dialogContext;

  void showProcessingDialog() {
    if (dialogContext != null && dialogContext!.mounted) {
      Navigator.pop(dialogContext!);
    }
    if (!context.mounted) {
      return;
    }
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (ctx) {
        dialogContext = ctx;
        return AlertDialog(content: child);
      },
    );
  }

  void dismissProcessingDialog() {
    if (dialogContext != null && dialogContext!.mounted) {
      Navigator.pop(dialogContext!);
    }
  }
}

Then you can use it like so:

final processingDialog =
    ProcessingDialog(context: context, child: const Text('Processing...'));
processingDialog.showProcessingDialog();
await Future.delayed(const Duration(seconds: 5));
processingDialog.dismissProcessingDialog();
0
 static Future<BuildContext?> wait(BuildContext context, String title) async {
   BuildContext? dialogContext;
   showDialog(
     context: context,
     builder: (BuildContext context) {
       dialogContext = context;
       return AlertDialog(
          backgroundColor: MyColors.color_primary_dark(),
          surfaceTintColor: MyColors.color_primary_dark(),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))),
          contentPadding: EdgeInsets.all(20),
          content: StatefulBuilder(builder: (BuildContext context, StateSetter setStatePopupMain) {
            return Column(mainAxisSize: MainAxisSize.min, children: [
              CircularProgressIndicator(strokeWidth: 2, color: MyColors.color_attention()),
              SizedBox(height: 20),
              MyText(title, color: MyColors.text_always_white()),
            ]);
          }));
    });
  await Future.delayed(const Duration(milliseconds: 100));
  return dialogContext;}

and use like this:

BuildContext? dialogContext= await  wait(context,"Loding...");
// do heveay work
Navigator.pop(dialogContext);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.