[英]Flutter swipe back gesture using nested navigators
I have a main navigator that push others child navigators, but if I push a route from a child navigator, on iOS when I swipe back from the open widget, it comes back to main navigator root instead to go to the root of the child widget, so how can I handle the history of the child navigator first with the swipe gesture and allow to go back on main navigator only if I'm on the root of the child (like a single navigator)?我有一个推送其他子导航器的主导航器,但是如果我从子导航器推送一条路线,在 iOS 上,当我从打开的小部件滑回时,它会返回到主导航器根目录,而不是 go 到子小部件的根目录,那么我如何才能首先使用滑动手势处理子导航器的历史记录,并且仅当我位于子导航器的根目录(如单个导航器)时才允许 go 回到主导航器?
This is the main navigator:这是主要的导航器:
class MenuNavigator extends StatelessWidget {
final GlobalKey<NavigatorState> navigatorKey;
const MenuNavigator({Key key, this.navigatorKey}) : super(key: key);
WidgetBuilder routeBuilder(
RouteSettings routeSettings, GetUserResponse userResponse) {
switch (routeSettings.name) {
case MenuNavigatorRoutes.root:
return (context) => MenuPage();
case MenuNavigatorRoutes.documents:
return (context) => DocumentsNavigator();
case MenuNavigatorRoutes.requests:
return (context) => RequestsNavigator();
default:
return null;
}
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
initialRoute: MenuNavigatorRoutes.root,
onGenerateRoute: (routeSettings) {
return MaterialPageRoute(
settings: routeSettings,
builder: (context) =>
routeBuilder(routeSettings, userResponse)(context));
},
);
}
}
DocumentsNavigator and RequestsNavigator are the child navigators and have the same structure of MenuNavigator but handle others routes. DocumentsNavigator 和 RequestsNavigator 是子导航器,具有与 MenuNavigator 相同的结构,但处理其他路由。
I just discovered that if you wrap your nested navigator with:我刚刚发现,如果您将嵌套导航器包装为:
WillPopScope(
child: NestedNavigator(initialRoute: ...),
onWillPop: () async =>
!Navigator.of(context).userGestureInProgress));
It works!有用!
This worked for me.这对我有用。 WillPopScope is only added when more then 1 page in nested navigator.
WillPopScope 仅在嵌套导航器中超过 1 页时添加。
@override
Widget build(BuildContext context) {
return NestedNavigator(
navigator: Navigator(
key: navigatorKey,
onPopPage: _handlePopPage,
pages: [],
),
);
}
import 'package:flutter/widgets.dart';
class NestedNavigator extends StatelessWidget {
const NestedNavigator({
super.key,
required this.navigator,
});
final Navigator navigator;
@override
Widget build(BuildContext context) {
if (navigator.pages.length > 1) {
return WillPopScope(
onWillPop: () async => !Navigator.of(context).userGestureInProgress,
child: navigator,
);
}
return navigator;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.