在颤动中打开对话框时检测后退按钮按下情况

问题描述 投票:0回答:4

我正在 flutter 中创建一个应用程序,我需要在其中显示警报对话框。这不是一个可以忽略的对话框。但是当我按下 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),
          ),
        ],
      );
    });}
android user-interface dialog flutter flutter-layout
4个回答
190
投票

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

showDialog(
  context: context,
  barrierDismissible: false,
  builder: (BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false, // False will prevent and true will allow to dismiss
      child: AlertDialog(
        title: Text('Title'),
        content: Text('This is Demo'),
        actions: <Widget>[
          FlatButton(
            onPressed: () => Navigator.pop(context),
            child: Text('Go Back'),
          ),
        ],
      ),
    );
  },
);

1
投票

阻止 Android 后退按钮关闭对话框的三种方法

选项一:

           onWillPop: () {
                          return Future.value(false);
                        },

选项二:

    onWillPop: () async {
                          return false;
                        },

选项三:

 onWillPop: () {}, // This will give surpress warning, try to avoid this one.

1
投票

因为我的声誉不足以对已接受的答案发表评论,所以我想为

onPressed: () {}
提供其他选择。您可以使用
onPressed: () => null
。不会弹出任何警告。


1
投票
 @override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: _onBackPressed,
          child: Scaffold(
            
          ),
        );
      }
    
      Future<bool> _onBackPressed() async {
        return await showDialog(
            context: context, builder: (context) => ExitAppDialogBox());
      }
© www.soinside.com 2019 - 2024. All rights reserved.