149

I have the following AlertDialog.

showDialog(
            context: context,
            child: new AlertDialog(
              title: const Text("Location disabled"),
              content: const Text(
                  """
Location is disabled on this device. Please enable it and try again.
                  """),
              actions: [
                new FlatButton(
                  child: const Text("Ok"),
                  onPressed: _dismissDialog,
                ),
              ],
            ),
        );

How can I make _dismissDialog() dismiss said AlertDialog?

Quick learner
  • 10,632
  • 4
  • 45
  • 55
Gustash
  • 1,523
  • 2
  • 8
  • 5

18 Answers18

236

Navigator.pop() should do the trick. You can also use that to return the result of the dialog (if it presented the user with choices)

Collin Jackson
  • 110,240
  • 31
  • 221
  • 152
  • 16
    Thank you, that worked. Calling Navigator.pop() closes out the dialog as expected. My current onPressed is as follows: `onPressed: () => Navigator.pop(context),` – Gustash May 24 '17 at 13:52
  • Worked for me as well! – Daniel Dec 12 '20 at 12:21
  • That's a fine solution, but there's a problem with that if AlertDialog is due to be closed automatically in 5 seconds, then if user taps elsewhere around dialog, thus closing dialog, after 5 seconds, `Navigator.pop(context)` redirects user back to the previous screen. Is there a solution that would specifically close specific AlertDialog, and not redirect user back if there is no AlertDialog? – Dalibor Oct 20 '22 at 21:05
164
Navigator.of(context, rootNavigator: true).pop('dialog')

worked with me.

Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
44
Navigator.pop(_)

worked for me, but the Flutter Team's gallery contains an example using:

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

which also works, and I am tempted to follow their lead.

Bryon Nicoson
  • 903
  • 11
  • 11
  • 1
    I calling a Custom AlertDialog from another .dart file and using Navigator.of(context, rootNavigator: true).pop(); worked thanks. – djalmafreestyler Apr 18 '20 at 17:08
  • 1
    I had always used the first version... but just ran into an example where the second one did, but the first removed the screen below it. – William Terrill Jul 24 '20 at 03:37
30

If you don't want to return any result, use either of them:

Navigator.of(context).pop();
Navigator.pop(context);

But if you do want to return some result, see this

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
  }
});
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
21

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 the result call, try

Navigator.pop(context,result);

OR

Navigator.of(context, rootNavigator: true).pop(result);
Vicky Salunkhe
  • 9,869
  • 6
  • 42
  • 59
9

Navigator.of(dialogContext).pop() otherwise you can close page if you navigated from Master to Detail page

                showDialog(
                  context: context,
                  builder: (dialogContext) {
                    return Dialog(
                      child: Column(
                        children: [
                          Text("Content"),
                          RaisedButton(
                            onPressed: () => Navigator.of(dialogContext).pop(),
                            child: Text("Close"),
                          )
                        ],
                      ),
                    );
                  },
                );
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
sultanmyrza
  • 4,551
  • 1
  • 30
  • 24
7

Example of dismissing alert dialog on flat button click

RaisedButton(
        onPressed: () {
          showDialog(
              context: context,
              builder: (context) => AlertDialog(
                    title: Text('Are you sure?'),
                    content: Text('Do you want to remove item?'),
                    actions: <Widget>[
                      FlatButton(
                          onPressed: () => Navigator.of(context).pop(false),//  We can return any object from here
                           child: Text('NO')),
                      FlatButton(
                          onPressed: () => Navigator.of(context).pop(true), //  We can return any object from here
                          child: Text('YES'))
                    ],
                  )).then((value) =>
              print('Selected Alert Option: ' + value.toString()));
        },
        child: Text('Show Alert Dialog'),
      ),

Above code have two unique things which is used to provide callback result of dialog

Navigator.of(context).pop(false) -- return false value when we pressed NO Navigator.of(context).pop(true) -- return true value when we pressed YES

Based on these return value, we can perform some operation outside of it or maintain the dialog status value

Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
4

This works Prefectly

      RaisedButton(
                child: Text(
                  "Cancel",
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
                onPressed: () => Navigator.pop(context),
              ),
Daya Nithi
  • 117
  • 1
  • 10
4

This worked for me Navigator.of(context, rootNavigator: true).pop('dialog').

Navigator.pop() just closes the current page/screen.

TuGordoBello
  • 4,350
  • 9
  • 52
  • 78
Prince Kelvin
  • 106
  • 1
  • 4
2

Creating a separate context for Alert Dialog would help.

showDialog(
  context: context,
  builder: (alertContext) => AlertDialog(
    title: const Text("Location disabled"),
    content: const Text(
        """Location is disabled on this device. Please enable it and try again."""),
    actions: [
      new FlatButton(
        child: const Text("Ok"),
        onPressed: () => Navigator.pop(alertContext),
      ),
    ],
  ),
);
KushalR
  • 251
  • 1
  • 2
  • 11
2

Please use following for code to close dialog

RaisedButton(
     onPressed: () { Navigator.of(context).pop();},
     child: Text("Close",style: TextStyle(color: Colors.white), ),
                color: Colors.black,
           )
1

Use Navigator.pop(context);

Example

showDialog(
            context: context,
            child: new AlertDialog(
              title: const Text("Location disabled"),
              content: const Text(
                  """
Location is disabled on this device. Please enable it and try again.
                  """),
              actions: [
                new FlatButton(
                  child: const Text("Ok"),
                  onPressed: () {
                      Navigator.pop(context);
                    },
                ),
              ],
            ),
        );
Quick learner
  • 10,632
  • 4
  • 45
  • 55
1

This answer works if you want to pop the dialog and navigate to another view. This part 'current_user_location' is the string the router need to know which view to navigate to.

FlatButton(
           child: Text('NO'),
           onPressed: () {
             Navigator.popAndPushNamed(context, 'current_user_location');
              },
           ),
Princeps Polycap
  • 220
  • 2
  • 16
1

This enough to dismisss dialog add inside Any callback like
onpressed,ontap

Navigator.of(context).pop();

    AlertDialog(
          title: Center(child: Text("$title")),
          insetPadding: EdgeInsets.zero,
          titlePadding: EdgeInsets.only(top: 14.0, bottom: 4),
          content: Container(
            height: 50,
            child: TextFormField(
              controller: find_controller,
              decoration: InputDecoration(
                suffixIcon: context.watch<MediaProvider>().isChangeDialog
                    ? IconButton(
                        onPressed: () {
                          clearController(find_controller);
                        },
                        icon: Icon(Icons.clear))
                    : null,
                border: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.deepPurpleAccent)),
                hintText: 'Id',
              ),
              onChanged: (val) {
                if (val.isNotEmpty)
                  context.read<MediaProvider>().isChangeDialog = true;
                else
                  context.read<MediaProvider>().isChangeDialog = false;
              },
            ),
          ),
          actions: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: OutlinedButton(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Align(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 12.0),
                              child: Icon(Icons.clear),
                            ),
                          ),
                          Text("Cancel")
                        ],
                      ),
                      onPressed: () {
                        context.read<MediaProvider>().isChangeDialog = false;
//========================this enough to dismisss dialog
                        Navigator.of(context).pop();
                      }),
                ),
                Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: ElevatedButton(
                      onPressed: context.watch<MediaProvider>().isChangeDialog
                          ? () {
                              context.read<MediaProvider>().isChangeDialog = false;
                              okCallback;
                            }
                          : null,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Align(
                            child: Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 12.0),
                              child: Icon(Icons.check),
                            ),
                          ),
                          Text("OK")
                        ],
                      )),
                )
              ],
            ),
          ],
        );

enter image description here

lava
  • 6,020
  • 2
  • 31
  • 28
1

For Closing Dialog

void cancelClick() {
    Navigator.pop(context);
  }
Safal Bhatia
  • 245
  • 2
  • 6
0

pass it in the showDialog barrierDismissible : true

0

use get package. then Get.back() to close Modal

-4

The accepted answer states how to dismiss a dialog using the Navigator Class. To dismiss a dialog without using Navigator you can set the onPressed event of the button to the following:

setState((){
  thisAlertDialog = null; 
});

In case the code above is not self-explanatory it is basically setting the Parent AlertDialog of the FlatButton to null, thus dismissing it.

otboss
  • 621
  • 1
  • 7
  • 16