[英]Flutter: Disable Swipe to Navigate Back in iOS and Android
我是 Flutter 开发的新手,当你有一个导航抽屉并且当你滑动打开它时,它会在 iOS 中发现它有点令人沮丧,它会执行Navigation.of(context).pop()
。 我想在 iOS 中禁用这种“滑动弹出”行为。 我一直在仔细阅读文档,但运气不佳。
我确实看到了一些被称为WillPopScope
东西,它似乎可以解决问题(此处为 github 问题),但我不能 100% 确定这是否是“正确”的方法(似乎太复杂了...它应该更容易......就像根应用程序上的设置一样)。
WillPopScope
是执行此操作的正确方法。
(这似乎太复杂了......它应该更容易......就像根应用程序上的设置一样)。
这并不复杂。 这是一个单班轮:
WillPopScope(
onWillPop: () async => false,
child: <children here>
)
配置文件会使事情变得更加复杂,因为它更难阅读和维护。
请记住,在 flutter 中,一切都是小部件,而不仅仅是其中的一半。 认证,配置,应有尽有。
我还有一点要补充。 我只是在解决这个问题,但我也需要我的用户能够通过按下 AppBar 上的“原生”后退按钮返回(不想因为这个而重新实现 AppBar),我发现了这个利基小标志:在 Navigator 对象上的userGestureInProgress
,所以我使用的(并且假定是首选方式)是:
onWillPop: () async {
if (Navigator.of(context).userGestureInProgress)
return false;
else
return true;
},
MaterialPageRoute
有一个名为fullscreenDialog
的参数,默认设置为 false。 当 true 时,您的页面动画会有所不同,并且在 iOS 上滑动返回将被禁用。
用法示例:
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => HomePage(), fullscreenDialog: true));
请参阅此处的一些讨论: https : //github.com/flutter/flutter/issues/14203
您可以在您的 Widget 版本中尝试此操作:
@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>,
);
}
好吧,正如@Darky 所说WillPopScope
是一个完全可以接受的答案,但是,如果您想全面禁用它,您实际上可以执行以下操作。
在 xcode 中打开您的项目,找到AppDelegate.swift
并添加以下内容:
let controller: FlutterViewController
= window?.rootViewController as! FlutterViewController;
controller.navigationController?
.interactivePopGestureRecognizer?.isEnabled = false;
我有一个类似的问题,我想阻止滑动以返回导航(默认弹出功能)。 此代码有助于解决问题。
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async => false,
child: Scaffold(
body: Center(
child: Text('Example'),
),
),
);
}
此代码现在阻止了 iOS 和 Android(默认后退按钮)的后退导航,这正是我正在寻找的。 希望这会有所帮助。
我不太确定你想要实现什么,但大多数时候人们想要摆脱后台功能,因为他们不想让用户控制身份验证机制。 例如,在用户登录后,您不希望他们通过按后退按钮(或在 iOS 中向后滑动)导航到登录页面。 一个潜在的解决方案是使用pushNamedAndRemoveUntil
。
Future<T> pushNamedAndRemoveUntil<T extends Object>(BuildContext context, String newRouteName, RoutePredicate predicate)
将具有给定名称的路由推送到最紧密包围给定上下文的导航器上,然后删除所有先前的路由,直到
predicate
返回 true。
示例代码: pushNamedAndRemoveUntil(context, '/home', ModalRoute.withName('/home'));
注意:一定程度上使用此方法,因为您可能会弄乱您的导航历史记录。
每当按下后退按钮或滑动手势(iOS)时,您都会在onWillPop
处收到一个回调,它返回一个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);
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.