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

Flutter GoRouter顶层redirect属性导致无法正常导航问题求助

Flutter GoRouter 顶层redirect导致无法跳转页面的解决方法

你当前遇到的问题是:点击跳转按钮本应进入ItemOne页面,却总是被重定向回首页/,日志显示每次尝试跳转/one都会被强制转到/。

问题原因

你的redirect逻辑存在错误——当前代码中,只要isAuth为true,不管用户要访问哪个路径,都会无条件重定向到/。也就是说,即使用户主动触发跳转/one,也会被这个规则拦截,强制回到首页。

解决方案

修改redirect函数逻辑,仅在用户未登录且访问的不是登录页面(此处为/one)时才进行重定向;已登录状态下允许正常访问所有页面,直接返回null表示不拦截路由。

修改后的GoRouter代码如下:

void main() => runApp(const NavApp());

const isAuth = true;

class NavApp extends StatelessWidget {
  const NavApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: GoRouter(
        debugLogDiagnostics: true,
        initialLocation: '/',
        redirect: (context, state) {
          // 未登录时,若当前访问的不是登录页则重定向到/one
          if (!isAuth && state.location != '/one') {
            return '/one';
          }
          // 已登录或已在登录页时,不进行重定向
          return null;
        },
        routes: [
          GoRoute(
            path: '/',
            builder: (context, state) => const NavHome(),
          ),
          GoRoute(
            path: '/one',
            builder: (context, state) => const ItemOne(),
          ),
        ],
      ),
    );
  }
}

逻辑说明

  • 当isAuth为true(已登录)时,redirect返回null,GoRouter会允许用户正常跳转到任何路由;
  • 当isAuth为false(未登录)时,只有用户访问非/one的路径才会被重定向到登录页,避免已登录状态下的不必要拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:55:42