How to dismiss an AlertDialog on a FlatButton click?
Asked Answered
H

18

154

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?

Hexose answered 24/5, 2017 at 13:28 Comment(0)
R
245

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)

Raychel answered 24/5, 2017 at 13:49 Comment(3)
Thank you, that worked. Calling Navigator.pop() closes out the dialog as expected. My current onPressed is as follows: onPressed: () => Navigator.pop(context),Hexose
Worked for me as well!Photoluminescence
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?Vanguard
S
166
Navigator.of(context, rootNavigator: true).pop('dialog')

worked with me.

Spittoon answered 2/7, 2018 at 18:24 Comment(6)
Accepted answer was causing my whole page to disappear, this is proper answer to hide a dialogBookstore
it is a better approach to close the dialog, I was trying above solution but it was poping my other view.Mignon
Accepted answer was causing my page to disappear too, this is the proper answer to hide a dialog.Lucinalucinda
The answer still causes the entire view to pop.Pomace
what is rootNavigator ?Garrido
Thank you very much for this answer. Fixes my progress dialog dismiss issue too.Vale
G
45
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.

Growler answered 22/9, 2018 at 16:49 Comment(2)
I calling a Custom AlertDialog from another .dart file and using Navigator.of(context, rootNavigator: true).pop(); worked thanks.Punctual
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.Suberin
D
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
  }
});
Dibasic answered 29/10, 2018 at 11:36 Comment(4)
What is the difference between these two lines of code ??Garrido
@user3410835 No difference, actually Navigator.pop() calls the the first line.Dibasic
How to make AlertDialog dismissable = false ? So that Dialog is not dismissed when i click on screen outside the dialog.Garrido
@user3410835 there is a property named barrierDismissible for the showDialog() and you can set it to false or true.Edlyn
S
23

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);
Strudel answered 7/12, 2020 at 13:24 Comment(2)
This is the best answerPea
I think this is the best answer too. Navigator.pop() worked on all my pages except this particular one which was opened through MaterialPageRouteNittygritty
F
10

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"),
                          )
                        ],
                      ),
                    );
                  },
                );
Futurity answered 23/9, 2020 at 11:15 Comment(0)
S
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

Sellars answered 17/4, 2020 at 10:4 Comment(2)
what will pop(false) do ? and what will pop(true) do ? Anyways in both the cases we want the AlertDialog to be dismissed.Garrido
@user3410835: Modified the code, please have a lookSellars
S
4

This works Prefectly

      RaisedButton(
                child: Text(
                  "Cancel",
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
                onPressed: () => Navigator.pop(context),
              ),
Stingaree answered 4/7, 2019 at 7:35 Comment(0)
I
4

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

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

Isar answered 22/10, 2020 at 14:27 Comment(0)
J
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),
      ),
    ],
  ),
);
Joerg answered 6/8, 2020 at 9:49 Comment(0)
T
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,
           )
Thatcher answered 23/8, 2020 at 15:16 Comment(0)
O
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);
                    },
                ),
              ],
            ),
        );
Oakleil answered 26/4, 2020 at 12:43 Comment(0)
W
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');
              },
           ),
Wellmannered answered 29/7, 2020 at 19:2 Comment(0)
H
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

Houseman answered 20/9, 2021 at 12:33 Comment(0)
I
1

For Closing Dialog

void cancelClick() {
    Navigator.pop(context);
  }
Illfavored answered 15/12, 2022 at 6:3 Comment(0)
L
0

pass it in the showDialog barrierDismissible : true

Lietman answered 7/9, 2020 at 13:33 Comment(0)
S
0

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

Shepley answered 29/4, 2022 at 6:37 Comment(0)
R
-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.

Randallrandan answered 5/1, 2019 at 13:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.