繁体   English   中英

如何在单击 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()应该可以解决问题。 您还可以使用它来返回对话框的结果(如果它向用户提供了选择)

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

和我一起工作。

Navigator.pop(_)

为我工作,但 Flutter 团队的画廊包含一个使用示例:

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

这也有效,我很想跟随他们的脚步。

如果您不想返回任何结果,请使用它们中的任何一个:

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

但是如果你确实想返回一些结果,请看这个

例子:

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

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

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) -- 当我们按下 NO 时返回 false 值 Navigator.of(context).pop(true) -- 当我们按下 YES 时返回 true 值

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

一般Navigator.pop(context); 作品。

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

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

如果要传递结果调用,请尝试

Navigator.pop(context,result);

要么

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

这很有效

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

Navigator.of(dialogContext).pop()否则,如果您从 Master 导航到 Detail 页面,则可以关闭页面

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

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

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

如果您想弹出对话框并导航到另一个视图,则此答案有效。 这部分“ 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传递它barrierDismissible : true

这对我有用 Navigator.of(context, rootNavigator: true).pop('dialog')。

Navigator.pop() 只是关闭当前页面/屏幕。

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

在此处输入图片说明

关闭对话框

void cancelClick() {
    Navigator.pop(context);
  }

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM