How to dismiss an AlertDialog on a FlatButton click?

AndroidIosFlutterFlutter Alertdialog

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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)

Solution 2 - Android

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

worked with me.

Solution 3 - Android

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.

Solution 4 - Android

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
  }
});

Solution 5 - Android

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);

Solution 6 - Android

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

Solution 7 - Android

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"),
                          )
                        ],
                      ),
                    );
                  },
                );

Solution 8 - Android

This works Prefectly

      RaisedButton(
                child: Text(
                  "Cancel",
                  style: TextStyle(color: Colors.white),
                ),
                color: Colors.blue,
                onPressed: () => Navigator.pop(context),
              ),

Solution 9 - Android

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);
                    },
                ),
              ],
            ),
        );

Solution 10 - Android

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),
      ),
    ],
  ),
);

Solution 11 - Android

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,
           )

Solution 12 - Android

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

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

Solution 13 - Android

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');
              },
           ),

Solution 14 - Android

You could wrap your AlertDialog in a async method to make the things clean.

  _showAlertConfirmDelete() async {
    // the response will store the .pop value (it can be any object you want)
    var response = await showDialog(
        context: context,
        builder: (context) => AlertDialog(
              title: Text('Warn'),
              content: Text('Really wants to remove the record?'),
              actions: <Widget>[
                FlatButton(
                    onPressed: () => Navigator.of(context)
                        .pop(false), 
                    child: Text('No')),
                FlatButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: Text('Yes'))
              ],
            ));
    // do you want to do with the response.
    print(response);
  }

Solution 15 - Android

pass it in the showDialog barrierDismissible : true

Solution 16 - Android

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

Solution 17 - Android

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

Solution 18 - Android

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGustashView Question on Stackoverflow
Solution 1 - AndroidCollin JacksonView Answer on Stackoverflow
Solution 2 - AndroidAbdulMomen عبدالمؤمنView Answer on Stackoverflow
Solution 3 - AndroidBryon NicosonView Answer on Stackoverflow
Solution 4 - AndroidCopsOnRoadView Answer on Stackoverflow
Solution 5 - AndroidVicky SalunkheView Answer on Stackoverflow
Solution 6 - AndroidJitesh MohiteView Answer on Stackoverflow
Solution 7 - AndroidsultanmyrzaView Answer on Stackoverflow
Solution 8 - AndroidDaya NithiView Answer on Stackoverflow
Solution 9 - AndroidQuick learnerView Answer on Stackoverflow
Solution 10 - AndroidKushalRView Answer on Stackoverflow
Solution 11 - AndroidKrishnamoorthy AcharyaView Answer on Stackoverflow
Solution 12 - AndroidPrince KelvinView Answer on Stackoverflow
Solution 13 - AndroidPrinceps PolycapView Answer on Stackoverflow
Solution 14 - AndroidCassio SeffrinView Answer on Stackoverflow
Solution 15 - AndroidcuriousmindView Answer on Stackoverflow
Solution 16 - AndroidlavaView Answer on Stackoverflow
Solution 17 - AndroidAlexis moussView Answer on Stackoverflow
Solution 18 - AndroidotbossView Answer on Stackoverflow