在GoRouter中使用ShellRoute时如何正确配置router.pop()
解决go_router中pop()返回错误路由的问题
针对你遇到的router.pop()/context.pop()直接跳转到/dashboard而非目标父路由的问题,可通过以下两种方式修复:
方案1:简化路由结构(推荐)
你当前在communityTab路由下嵌套了一个仅返回child的ShellRoute,这种冗余结构会干扰路由栈的层级关系。直接将profileSubrouteFromCommunity作为communityTab的子路由即可:
修改后的社区路由代码:
final communityTab = GoRoute( name: ROUTE.community_tab_selected, path: '/community_tab_selected/:index', pageBuilder: (context, state) { return createRoutePage( state.pageKey, DashboardPage( initialIndex: "1", communityTabParams: CommunityChannelPageQueryParams.fromJson(state.pathParameters), ), opaque: false, ); }, routes: [ profileSubrouteFromCommunity, // 移除ShellRoute,直接挂载子路由 ], );
修改后,在个人资料页调用context.pop()就能正确返回/community_tab_selected/0。
方案2:使用popUntil精准定位路由(保留ShellRoute场景)
如果因业务需求必须保留ShellRoute,可通过popUntil方法指定返回的目标路由名称,避免直接pop跳转到根路由:
在个人资料页的返回按钮逻辑中替换为:
// 方式1:使用context的popUntil context.popUntil(ModalRoute.withName(ROUTE.community_tab_selected)); // 方式2:使用GoRouter实例的popUntil GoRouter.of(context).popUntil((route) => route.name == ROUTE.community_tab_selected);
该方法会遍历路由栈,直到匹配到名称为ROUTE.community_tab_selected的路由,确保返回正确的父页面。
内容的提问来源于stack exchange,提问作者Maruf Hassan
相关产品推荐
相关产品推荐

