有什么方法可以从 Android 后退按钮捕获 onBackPressed
事件?
我尝试了 WillPopScope
但我的 onWillPop
功能仅在我点击 Material 返回箭头按钮时触发
我是这样说的:
class MyView extends StatelessWidget{
Widget build(BuildContext context) {
return new WillPopScope(
onWillPop: () async {
debugPrint("Will pop");
return true;
},
child: ScopedModel<AppModel>(
model: new AppModel(),
child: new Scaffold(......
我需要捕获它,因为不知何故我的屏幕在按下后退按钮时表现不正确,它会弹出屏幕及其下方的屏幕,但不知何故,使用 Material 后退箭头按钮工作正常。
更新:
代码有效,我的问题不在此屏幕的弹出窗口中,而是在上一个屏幕上,我使用了 2 个 MaterialApp 小部件,不知何故它给出了一种奇怪的行为。
最佳答案
为了防止返回 WillPopScope是正确的方法,应该如下使用:
class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new WillPopScope(
child: new Scaffold(
appBar: new AppBar(
title: new Text('Page 2'),
),
body: new Center(
child: new Text('PAGE 2'),
),
),
onWillPop: () async {
return false;
},
);
}
}
Future<T> pushPage<T>(BuildContext context, Widget page) {
return Navigator.of(context)
.push<T>(MaterialPageRoute(builder: (context) => page));
}
可以像这样调用页面:
pushPage(context, Page2());
关于android - 在 Flutter 上捕获 Android 后退按钮事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452710/