我用WillPopScope
覆盖了我的Scaffold
,但在iOS上滑动返回时不会调用onWillPop
回调。
这可能是什么原因呢?
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
print("onWillPop"); // is not printed to the console
if (Navigator.of(context).userGestureInProgress)
return false;
else
return true;
},
child: new Scaffold(
appBar: new AppBar(
title: new Text("App Title"),
),
body: Stack(
children: <Widget>[
...widgets...
],
),
),
);
}
发布于 2022-01-25 11:16:11
正如前面提到的getter,为了让你的WillPopScope工作,你应该像这样覆盖MaterialPageRoute中的hasScopedWillPopCallback getter:
class CustomMaterialPageRoute extends MaterialPageRoute {
@protected
bool get hasScopedWillPopCallback {
return false;
}
CustomMaterialPageRoute({
@required WidgetBuilder builder,
RouteSettings settings,
bool maintainState = true,
bool fullscreenDialog = false,
}) : super(
builder: builder,
settings: settings,
maintainState: maintainState,
fullscreenDialog: fullscreenDialog,
);
}
然后在您的路由器中更换CustomMaterialPageRoute上的MaterialPageRoute。这肯定会让WillPopScope在IOS和Android平台上都能工作。
发布于 2019-08-05 19:19:42
我找到了原因: WillPopScope无法工作,因为使用上述构建方法的小部件不是顶级小部件(由main调用的小部件)。我希望它能帮助其他人。
发布于 2021-09-08 09:55:19
这是一个问题,在本issue中讨论了很多,但是有一种方法可以解决它,那就是使用this package
return ConditionalWillPopScope(
child: _MyScreenContent(),
onWillPop: _onWillPop,
shouldAddCallbacks: _hasChanges,
);
https://stackoverflow.com/questions/57356879
复制相似问题