在对话框打开时检测后退按钮按下

Gau*_*rav 9 user-interface android dialog flutter flutter-layout

我正在创建一个应用程序,我需要显示一个警告对话框.这不是一个可以容忍的对话.但是当我按下Android上的按钮时,它会被解雇.我尝试使用WillPopScope小部件来检测反压事件.我可以使用WillPopScope检测后退按钮按下但是在对话框打开时这不起作用.任何建议和指南都会非常有用.谢谢.

对话框创建代码段:

void buildMaterialDialog(
  String dialogTitle,
  String dialogContent,
  String negativeBtnText,
  String positiveBtnText,
  String positiveTextUri) {

showDialog(
    context: context,
    barrierDismissible: false,
    builder: (BuildContext context) {
      return new AlertDialog(
        title: new Text(dialogTitle),
        content: new Text(dialogContent),
        actions: <Widget>[
          new FlatButton(
            onPressed: () {
              //Function called
              _updateDialogNegBtnClicked(isCancelable);
            },
            child: new Text(negativeBtnText),
          ),
          new FlatButton(
            onPressed: () => launch(positiveTextUri),
            child: new Text(positiveBtnText),
          ),
        ],
      );
    });}
Run Code Online (Sandbox Code Playgroud)

anm*_*ail 23

后退按钮不会关闭对话框.

showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return WillPopScope(
                                onWillPop: () {},
                                child: new AlertDialog(
                                  title: new Text('Title'),
                                  content: new Text('This is Demo'),
                                  actions: <Widget>[
                                    new FlatButton(
                                      onPressed: () {
                                        //Function called
                                      },
                                      child: new Text('Ok Done!'),
                                    ),
                                    new FlatButton(
                                      onPressed: () {
                                        Navigator.pop(context);
                                      },
                                      child: new Text('Go Back'),
                                    ),
                                  ],
                                ),
                              );
                            });
Run Code Online (Sandbox Code Playgroud)

  • 那很棒。但是一直以来,我一直在onWillPop内部返回Future,例如onWillPop:(){return Future.value(false);}`。从来没有知道它可以没有! (4认同)
  • 或者我们可以使用'()async =&gt; false' (4认同)
  • 如果您已经使用了 `WillPopScope()`,则不再需要 `barrierDismissible = false` (4认同)

小智 5

伙计们!我来自 2023 年)WillPopScope 方法已更新:

PopScope(canPop: false, child: AlertDialog())
Run Code Online (Sandbox Code Playgroud)