【发布时间】:2021-05-28 00:50:26
【问题描述】:
我正在使用自定义 Navigator 小部件并使用 WillPopScope 包装它来处理我的应用程序中的路由。
但是在弹出或推送时,我遇到了获取堆栈顶部的确切路线的问题。我需要检测这些更改以始终在应用栏中显示当前路线名称。
我为此使用ModalRoute.of(navigatorKey.currentContext).settings.name,但打印的路线始终是“/”,即使切换页面并使用后退按钮弹出它们效果很好。
在我的main.dart 的脚手架内:
WillPopScope(
onWillPop: () async {
if (navigatorKey.currentState.canPop()) {
//trying to catch name of the route during pop. results always "/"
print(ModalRoute.of(navigatorKey.currentContext).settings.name);
navigatorKey.currentState.pop();
return false;
}
return true;
},
child: Navigator(
key: navigatorKey,
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
//Each route(page) has one big button on it which leads to the next route
//(BTW, stack is simple, linear, ProductChoice -> ShapeChoice -> ShapeEditor -> More
// and reverse is the only possible way to navigate, for max simplicity)
Map<String, Widget> pages = {
"/": ProductChoice(
navigatorKey: navigatorKey,
swipeDownCallback: () {},
),
"/shapeChoice": ShapeChoice(
navigatorKey: navigatorKey,
swipeDownCallback: () {},
),
"/shapeEditor": ShapeEditor(
navigatorKey: navigatorKey,
shapeName: glassDataState.current["dimensions"]["shapeName"],
swipeDownCallback: () {},
),
"/more": More(),
};
//Could it be pageTransition's fault? Animations seem to work fine
return pageTransition(pages[settings.name], Offset(1, 0));
},
),
),
我将 navigatorKey 传递给路由,以便每条路由上的每个按钮都可以执行此操作(例如:ProductChoice):
return BigButton(
title: title,
onClick: () {
navigatorKey.currentState.pushNamed("/shapeChoice");
每页还有第二个按钮,用来返回:
navigatorKey.currentState.pop();
就这么简单,但是ModalRoute.of(navigatorKey.currentContext).settings.name 到处都返回“/”。
我也试过:ModalRoute.of(context).settings.name,结果相同。
不确定pageTransition 是否重要,但无论如何:
Route pageTransition(Widget toPage, Offset begin) {
return PageRouteBuilder(
pageBuilder: (context, animation, secondaryAnimation) => toPage,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
// var begin = Offset(0.0, 1.0);
var end = Offset.zero;
var curve = Curves.fastOutSlowIn;
var tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curve));
return SlideTransition(
position: animation.drive(tween),
child: child,
);
},
);
}
感谢您的帮助!
【问题讨论】:
标签: flutter dart navigator stack-navigator