Flutter开发:如何通过go_router阻止路由变更?
GoRouter导航拦截实现方案
GoRouter本身并没有你示例中命名为listener的参数,但可以通过以下两种方式实现导航栈修改前的拦截逻辑,比如阻止深层链接重复叠加:
1. 全局redirect函数
通过GoRouter构造器的redirect参数,实现全局范围的导航拦截判断:
GoRouter( routes: [ GoRoute(path: '/', builder: (context, state) => const HomePage()), GoRoute(path: '/home/details', builder: (context, state) => const DetailsPage()), ], redirect: (context, state) { // 获取当前的导航栈位置 final currentLocation = GoRouter.of(context).location; // 示例:如果尝试跳转的是详情页且当前已经在详情页,阻止导航 if (state.location == '/home/details' && currentLocation == '/home/details') { // 返回null表示拦截本次导航,保持当前状态 return null; } // 返回目标路径则允许导航,返回null则拦截 return state.location; }, )
2. 路由级beforeEnter钩子
针对特定路由配置beforeEnter,实现局部的导航拦截:
GoRoute( path: '/home/details', builder: (context, state) => const DetailsPage(), beforeEnter: (context, state) { // 检查当前导航栈中是否已存在该路由 final hasDetailsRoute = GoRouter.of(context) .routerDelegate .currentConfiguration .any((route) => route.location == '/home/details'); // 返回false阻止进入该路由,返回true允许进入 return !hasDetailsRoute; }, )
如果需要监听所有导航栈的变化细节,还可以自定义NavigatorObserver类,但上述两种方式已经能覆盖大部分拦截需求。
内容的提问来源于stack exchange,提问作者Ilia Zadiabin
相关产品推荐
相关产品推荐

