我刚开始学习Flutter开发,在iOS上使用导航抽屉时,当您滑动打开它时,会执行Navigation.of(context).pop()
。我想在iOS中禁用这种“滑动返回”行为。我一直在查阅相关文档,但没有什么收获。
我看到有人提到了一个WillPopScope
,似乎可以解决问题(GitHub的问题页面在此处),但我不确定这是否是“正确”的方法(它似乎太复杂了……应该更简单些,比如在根应用程序中设置一个选项)。
我刚开始学习Flutter开发,在iOS上使用导航抽屉时,当您滑动打开它时,会执行Navigation.of(context).pop()
。我想在iOS中禁用这种“滑动返回”行为。我一直在查阅相关文档,但没有什么收获。
我看到有人提到了一个WillPopScope
,似乎可以解决问题(GitHub的问题页面在此处),但我不确定这是否是“正确”的方法(它似乎太复杂了……应该更简单些,比如在根应用程序中设置一个选项)。
WillPopScope
是正确的方法。
(看起来有些复杂... 应该更简单... 就像根应用程序上的一个设置一样)。
它并不复杂。只需要一行代码:
WillPopScope(
onWillPop: () async => false,
child: <children here>
)
使用配置文件会使事情变得更加复杂,因为它更难阅读和维护。
并且请记住在Flutter中所有东西都是小部件,而不仅仅是其中的一半。认证、配置,一切皆是如此。
userGestureInProgress
在Navigator对象上,所以我使用的是(并且假设这是首选的方式):onWillPop: () async {
return !Navigator.of(context).userGestureInProgress;
},
onWillPop: () async => !Navigator.of(context).userGestureInProgress
- TheFabbiusMaterialPageRoute
有一个名为fullscreenDialog
的参数,默认情况下设置为false。当设置为true时,您的页面将以稍微不同的动画显示,并且在iOS上向右滑动返回功能将被禁用。
示例用法:
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => HomePage(), fullscreenDialog: true));
@override
Widget build(BuildContext context) {
return WillPopScope(//forbidden swipe in iOS(my ThemeData(platform: TargetPlatform.iOS,)
onWillPop: ()async {
if (Navigator.of(context).userGestureInProgress)
return false;
else
return true;
},
child: <your child>,
);
}
onWillPop: () async => !(Navigator.of(context).userGestureInProgress),
- wattson我曾经遇到一个类似的问题,想要在导航中阻止向后滑动以返回(默认的弹出函数)。这段代码帮助解决了问题。
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
body: Center(
child: Text('Example'),
),
),
);
}
这段代码现在可以阻止iOS和Android的后退导航(默认后退按钮),这正是我想要的。希望对你有所帮助。
好的,如@Darky所说,WillPopScope
是一个完全可接受的答案,然而,如果您想要在整个应用中禁用它,您可以实际上执行以下操作。
在xcode中打开您的项目,找到AppDelegate.swift
并添加以下内容:
let controller: FlutterViewController
= window?.rootViewController as! FlutterViewController;
controller.navigationController?
.interactivePopGestureRecognizer?.isEnabled = false;
MaterialApp
或 WidgetApp
。 - Rémi RousseletMaterialApp
的根部,但是遗憾的是没有。:'( - James GilchristWillPopScope
中。应该很容易。 - Rémi RousseletonWillPop
处得到一个回调函数。该回调函数返回一个Future
对象。如果Future
对象返回true,则屏幕会被弹出(即导航到前一个屏幕);如果它返回false,则不会向后导航。Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
return Future.value(false);
},
child: Scaffold(
appBar: AppBar(title: Text("Second Screen"),),
body: Center(
如果您想根据条件弹出屏幕,则声明
bool shouldPop = true; // change this using setState() inside build on the requirement.
onWillPop: () {
return Future.value(shouldPop? true: false);
},
pushNamedAndRemoveUntil
。
Future<T> pushNamedAndRemoveUntil<T extends Object>(BuildContext context, String newRouteName, RoutePredicate predicate)
引用:predicate
返回true。pushNamedAndRemoveUntil(context, '/home', ModalRoute.withName('/home'));
注意:请谨慎使用此方法,因为您可能会弄乱导航历史记录。
return true;
)的同时利用WillPopScope
呢? - Jonathan Rhein