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

Flutter GoRouter刷新浏览器时重置至应用初始页面问题求助

问题分析与解决方法

问题根源

你遇到的刷新后路由重置问题,核心原因是mainWrapperPage路由的无条件重定向。页面刷新时,GoRouter会重新解析URL:当当前URL是/#/main/settings时,GoRouter会先匹配到ShellRoute下的mainWrapperPage(因为/main是父路径),然后触发它的redirect逻辑,直接跳转到/main/dashboard,导致原URL被覆盖。

解决步骤

修改mainWrapperPage的redirect逻辑,仅当当前路径严格等于/main时才执行重定向,而不是无条件跳转:

GoRoute(
  path: EvRoute.mainWrapperPage.path, // Path is /#/main
  name: EvRoute.mainWrapperPage.name,
  redirect: (context, state) {
    // 只有当当前路径正好是/main时,才重定向到dashboard
    if (state.subloc == EvRoute.mainWrapperPage.path) {
      return EvRoute.dashboardPage.path;
    }
    return null; // 其他路径(如/main/settings)不触发重定向
  },
),

原理说明

  • 刷新时,GoRouter会正确解析完整URL(如/#/main/settings),此时state.subloc的值是/main/settings,不会触发mainWrapperPage的重定向逻辑。
  • ShellRoute的认证检查redirect仅在用户未登录时跳转登录页,已登录状态下不会干扰子路由的匹配,保证当前URL对应的页面正常渲染。

额外验证点

确认你的路由路径层级正确:

  • EvRoute.dashboardPage.path应为/main/dashboard
  • EvRoute.settingsPage.path应为/main/settings
    确保这两个路由是ShellRoute的直接子路由,没有嵌套层级错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:27:19