Flutter 无法从方法“_onBackPress”返回“Future<dynamic>”类型的值,因为它的返回类型为“Future<bool>”

Div*_*ani 2 flutter flutter-test flutter-layout

我正在我的应用程序中处理后退按钮,但我在颤动中遇到了这个问题\n非常感谢高级\我之前使用此功能执行过此操作,但现在它不起作用\我认为是因为空安全\n对不起我英语不好\n截图

\n

这是我的扑动医生

\n
Doctor summary (to see all details, run flutter doctor -v):\n[\xe2\x88\x9a] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19043.1110], locale en-US)\n[\xe2\x88\x9a] Android toolchain - develop for Android devices (Android SDK version 30.0.3)\n[\xe2\x88\x9a] Chrome - develop for the web\n[\xe2\x88\x9a] Android Studio (version 4.1.0)\n[\xe2\x88\x9a] VS Code (version 1.58.2)\n[\xe2\x88\x9a] Connected device (3 available)\n\n\xe2\x80\xa2 No issues found!\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的构建方法和 Future 函数

\n
Future<bool> _onBackPress() {\n    return showDialog(\n      context: context,\n      builder: (BuildContext context) {\n        return AlertDialog(\n          content: Text(\'Exit From The App\'),\n          actions: [\n            TextButton(\n              onPressed: () {\n                Navigator.of(context).pop(false);\n              },\n              child: Text(\'No\'),\n            ),\n            TextButton(\n              onPressed: () {\n                Navigator.of(context).pop(true);\n              },\n              child: Text(\'Yes\'),\n            ),\n          ],\n        );\n      },\n    );\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return WillPopScope(\n      onWillPop: _onBackPress,\n      child: Scaffold(\n        appBar: AppBar(\n          automaticallyImplyLeading: false,\n          brightness: Brightness.dark,\n          title: Text(\'Internet Availability Checker\'),\n        ),\n      ),\n    );\n  }\n
Run Code Online (Sandbox Code Playgroud)\n

小智 6

showDialog 是一个异步函数,这意味着它将等待直到出现结果。在这种情况下 - 直到对话框关闭。因为它是异步的,所以您可以在 showDialog 右括号之后添加 .then(意思是“当收到值时”)。

.then((值) => 值??假);

顺便说一句,默认情况下“值”为空,当您尝试点击对话框区域之外来处理它时,它将为空。为了避免空返回,请使用“??” 检查将默认值(如果为 null)设置为 false

 Future<bool> _onBackPress() {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Text('Exit From The App'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(false);
              },
              child: Text('No'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(true);
              },
              child: Text('Yes'),
            ),
          ],
        );
      },
    ).then((value) => value ?? false);
  }
Run Code Online (Sandbox Code Playgroud)