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

如何使用go_router包实现基于登录状态的动态初始路由?

解决GoRouter启动时根据登录状态跳转特定路由的问题

当使用MaterialApp.router时,home和initialRoute参数确实不再生效,需要通过GoRouter自身的配置来实现启动时的路由跳转,以下是两种常用方案:


方案1:使用redirect重定向(推荐,支持实时状态更新)

GoRouter的redirect配置可以在路由跳转前执行逻辑判断,不仅能处理启动时的跳转,还能在用户登录状态变化时自动重定向。

示例代码:

final router = GoRouter(
  routes: [
    GoRoute(
      path: '/login',
      builder: (context, state) => LoginPage(),
    ),
    GoRoute(
      path: '/home',
      builder: (context, state) => HomePage(),
    ),
  ],
  // 重定向逻辑
  redirect: (context, state) {
    // 替换为你的登录状态判断逻辑(比如从状态管理/本地存储获取)
    final isLoggedIn = AuthService.instance.isLoggedIn;

    // 未登录且当前不在登录页 → 跳转到登录页
    if (!isLoggedIn && state.location != '/login') {
      return '/login';
    }
    // 已登录且当前不在首页 → 跳转到首页
    if (isLoggedIn && state.location != '/home') {
      return '/home';
    }
    // 返回null表示不执行重定向
    return null;
  },
);

方案2:动态设置initialLocation(启动时一次性判断)

如果只需要在应用启动时判断一次登录状态,可以直接在初始化GoRouter时动态赋值initialLocation。

同步判断场景:

final router = GoRouter(
  // 根据登录状态直接设置初始路由
  initialLocation: AuthService.instance.isLoggedIn ? '/home' : '/login',
  routes: [
    GoRoute(path: '/login', builder: (_,__) => LoginPage()),
    GoRoute(path: '/home', builder: (_,__) => HomePage()),
  ],
);

异步判断场景(比如从本地存储读取登录状态):

如果登录状态需要异步获取,需要在main函数中先完成异步操作再初始化应用:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 异步获取登录状态
  final isLoggedIn = await AuthService.instance.checkLoginStatus();
  
  runApp(MyApp(isLoggedIn: isLoggedIn));
}

class MyApp extends StatelessWidget {
  final bool isLoggedIn;
  
  const MyApp({super.key, required this.isLoggedIn});

  @override
  Widget build(BuildContext context) {
    final router = GoRouter(
      initialLocation: isLoggedIn ? '/home' : '/login',
      routes: [
        GoRoute(path: '/login', builder: (_,__) => LoginPage()),
        GoRoute(path: '/home', builder: (_,__) => HomePage()),
      ],
    );
    
    return MaterialApp.router(
      restorationScopeId: 'app',
      debugShowCheckedModeBanner: false,
      routerConfig: router,          
    );
  }
}

内容的提问来源于stack exchange,提问作者Titas Černiauskas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:22:15