如何在单击 FlatButton 时关闭 AlertDialog?

How to dismiss an AlertDialog on a FlatButton click?

我有以下 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,
                ),
              ],
            ),
        );

我怎样才能让 _dismissDialog() 驳回说 AlertDialog

Navigator.pop() 应该可以解决问题。您还可以将其用于 return 对话框的结果(如果它向用户提供了选择)

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

和我一起工作。

Navigator.pop(_)

对我有用,但 Flutter Team 的画廊包含一个示例使用:

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

这也行得通,我很想效仿他们。

如果您不想return任何结果,请使用其中之一:

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

但如果您确实想要 return 一些结果,请参阅此

示例:

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

已接受的答案说明了如何使用导航器关闭对话框 Class。要在不使用 Navigator 的情况下关闭对话框,您可以将按钮的 onPressed 事件设置为以下内容:

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

如果上面的代码不言自明,它基本上是将 FlatButton 的 Parent AlertDialog 设置为 null,从而将其关闭。

这很好用

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

单击平面按钮时关闭警报对话框的示例

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

以上代码有两个独特之处,用于提供对话框的回调结果

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

基于这些return值,我们可以在它之外执行一些操作或者维护对话状态值

使用Navigator.pop(context);

示例

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

如果您想弹出对话框并导航到另一个视图,则此答案有效。这部分“current_user_location”是路由器需要知道要导航到哪个视图的字符串。

FlatButton(
           child: Text('NO'),
           onPressed: () {
             Navigator.popAndPushNamed(context, 'current_user_location');
              },
           ),

为警报对话框创建一个单独的上下文会有所帮助。

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

请使用以下代码关闭对话框

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

您可以将 AlertDialog 包装在一个异步方法中以使事情变得干净。

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

在showDialog中传递 barrierDismissible : true

Navigator.of(dialogContext).pop() 否则,如果您从主页面导航到详细信息页面,您可以关闭页面

                showDialog(
                  context: context,
                  builder: (dialogContext) {
                    return Dialog(
                      child: Column(
                        children: [
                          Text("Content"),
                          RaisedButton(
                            onPressed: () => Navigator.of(dialogContext).pop(),
                            child: Text("Close"),
                          )
                        ],
                      ),
                    );
                  },
                );

这有效 for me Navigator.of(context, rootNavigator: true).pop('dialog')

Navigator.pop() 只是关闭当前 page/screen.

通常 Navigator.pop(context); 有效。

但是如果应用程序有多个 Navigator 对象并且 dialogBox 没有关闭,那么试试这个

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

如果你想传递结果调用,试试

Navigator.pop(context,result);

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

这足以关闭在回调 luke 中添加的对话框
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")
                        ],
                      )),
                )
              ],
            ),
          ],
        );

使用获取包。 然后 Get.back() 关闭 Modal