You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用go_router(Navigator 2.0)实现循环递归路由

用GoRouter实现带完整栈状态的递归循环路由

要实现用户页→帖子页→用户页→帖子页这种保留完整导航栈的递归路由,GoRouter不需要在静态路由表中做递归声明,而是利用动态push导航来实现,具体方案如下:

1. 简化静态路由表定义

不需要在PostPage的子路由中嵌套UserPage,保持基础的路由层级即可:

final GoRouter router = GoRouter(
  routes: [
    GoRoute(
      path: '/users/:user_id',
      builder: (context, state) => UserPage(id: state.pathParameters['user_id']!),
      routes: [
        GoRoute(
          path: 'posts/:post_id',
          builder: (context, state) => PostPage(id: state.pathParameters['post_id']!),
          // 无需在此递归声明User路由,通过动态push实现嵌套
        ),
      ],
    ),
  ],
);

2. 使用push方法触发递归导航

在需要跳转到下一层页面时,调用context.push()而不是context.go()——push会将新页面添加到当前导航栈的顶部,完全保留之前的页面状态和栈结构:

在PostPage中跳转到新的用户页

// PostPage内的跳转逻辑示例
ElevatedButton(
  onPressed: () {
    // 替换为实际要跳转的用户ID
    const targetUserId = '123';
    context.push('/users/$targetUserId');
  },
  child: const Text('查看该用户主页'),
);

在UserPage中跳转到对应帖子页

// UserPage内的跳转逻辑示例
ElevatedButton(
  onPressed: () {
    // 替换为当前用户的目标帖子ID
    const targetPostId = '456';
    context.push('/users/${widget.id}/posts/$targetPostId');
  },
  child: const Text('查看我的帖子'),
);

3. 效果说明

通过这种方式,导航栈会完整保留每一层页面:

  • 导航流程:UserPage(A) → PostPage(1) → UserPage(B) → PostPage(2)
  • 返回流程:PostPage(2) → UserPage(B) → PostPage(1) → UserPage(A)

关键注意事项

  • 禁止使用context.go():go方法会替换整个导航栈,导致之前的页面状态全部丢失;
  • 页面状态独立:确保UserPage和PostPage根据传入的ID渲染对应内容,避免状态复用导致的显示错误;
  • 内存优化:如果栈深度较大,可在页面dispose时清理非必要资源,避免内存泄漏。

内容的提问来源于stack exchange,提问作者nyarian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:25:01