flutter - android 后退按钮不会调用 WillPopScope 的 onWillPop

Gic*_*nos 11 dart flutter

我想退出我的应用程序。我已经实现了一个 WillPopScope,但看起来根本没有调用 onWillPop 函数。我尝试了很多想法,例如将 WillPopScope 与 Scaffold 交换,更改函数的返回值,但看起来它没有按预期工作。

我的代码:

Future<bool> _willPopCallback() async {
  exit(0);
  // await showDialog or Show add banners or whatever
  // then
  return true; // return true if the route to be popped
}


return Scaffold(
    appBar: MyAppBar(
      leading: DrawerAction(),
      title: Text(AppLocalizations.of(context).textCapitalized('home_page')),
      onSearch: (searchTerms) => this.search(searchTerms, context),
    ),
    body: new WillPopScope(
      onWillPop: _willPopCallback, // Empty Function.
      child: //my screen widgets
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是我应该向 flutter 报告的错误,或者我做错了什么。很高兴根据要求提供更多代码。

我试过了:

exit(0);
Navigator.of(context).pop();
SystemChannels.platform.invokeMethod('SystemNavigator.pop');
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Has*_*ilT 12

首先永远不要使用exit(0). 在Android环境下可能没问题,但如果应用程序以编程方式自行关闭,Apple将不允许该应用程序出现在应用程序商店中。

这里在它的文档中onWillPop清楚地提到函数应该解析为一个布尔值。

Future<bool> _willPopCallback() async {
   // await showDialog or Show add banners or whatever
   // then
   return Future.value(true);
}
Run Code Online (Sandbox Code Playgroud)

这仅在您当前页面是导航堆栈的根时才有效。

  • 我将再次尝试使用“Future.value(true)”,但我再说一遍,函数 _willPopCallback() 不会被 WillPopScope 调用! (2认同)

Gic*_*nos 11

我设法解决了我的问题,我认为这是一个非常特殊的案例,但它仍然可能对某人有所帮助。

TL;DR:确保您的小部件中没有多个 Scaffolds

我IndexedStack在我的菜单导航器中使用,显然用脚手架包裹。堆栈的页面也有 Scaffold,这种组合WillPopScope在导航器页面和堆栈页面中都不起作用。我通过删除堆栈页面中的所有 Scaffolds 并在控制器中只有一个来解决。通过这种方式,我设法WillPopScope正确使用。