flutter中如何使用go_router实现导航守卫功能

在Flutter项目中使用go_router时,如何实现类似导航守卫的功能?比如在用户未登录时自动跳转到登录页,或者在特定路由切换前进行权限校验。go_router文档中提到的redirect似乎可以实现,但不太清楚具体如何编写逻辑。能否提供一个完整的示例,包括如何根据auth状态动态控制路由跳转?

2 回复

在Flutter中使用go_router实现导航守卫,可通过redirect回调。示例:

GoRouter(
  redirect: (context, state) {
    // 检查登录状态
    if (!isLoggedIn && state.location != '/login') {
      return '/login';
    }
    return null; // 允许导航
  },
  routes: [...],
)

redirect中根据条件返回重定向路径或null允许原路径。

更多关于flutter中如何使用go_router实现导航守卫功能的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在 Flutter 中使用 go_router 实现导航守卫功能,主要通过 GoRouterredirect 属性和 refreshListenable 实现。以下是具体步骤和示例代码:

1. 基本导航守卫(重定向)

使用 redirect 属性在路由跳转前进行条件判断,决定是否重定向到其他路径。

import 'package:go_router/go_router.dart';

final goRouter = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => HomePage(),
    ),
    GoRoute(
      path: '/login',
      builder: (context, state) => LoginPage(),
    ),
    GoRoute(
      path: '/profile',
      builder: (context, state) => ProfilePage(),
    ),
  ],
  redirect: (context, state) {
    // 检查用户是否已登录(假设使用一个简单的状态管理)
    final isLoggedIn = AuthService.isLoggedIn; // 替换为实际认证状态
    
    // 如果未登录且尝试访问需要认证的页面(如 /profile),重定向到登录页
    final goingToProfile = state.matchedLocation == '/profile';
    if (!isLoggedIn && goingToProfile) {
      return '/login';
    }
    
    // 如果已登录但访问登录页,重定向到首页
    if (isLoggedIn && state.matchedLocation == '/login') {
      return '/';
    }
    
    // 否则允许正常导航
    return null;
  },
);

2. 动态状态监听(高级守卫)

结合 refreshListenable 监听认证状态变化,实现动态重定向。

class AuthNotifier extends ChangeNotifier {
  bool _isLoggedIn = false;
  
  bool get isLoggedIn => _isLoggedIn;
  
  void login() {
    _isLoggedIn = true;
    notifyListeners(); // 触发路由刷新
  }
  
  void logout() {
    _isLoggedIn = false;
    notifyListeners();
  }
}

final authNotifier = AuthNotifier();

final goRouter = GoRouter(
  refreshListenable: authNotifier, // 监听认证状态变化
  routes: [ ... ], // 同上
  redirect: (context, state) {
    final isLoggedIn = authNotifier.isLoggedIn;
    final goingToProfile = state.matchedLocation == '/profile';
    
    if (!isLoggedIn && goingToProfile) {
      return '/login';
    }
    if (isLoggedIn && state.matchedLocation == '/login') {
      return '/';
    }
    return null;
  },
);

3. 使用方式

在 Flutter 应用中配置路由:

void main() {
  runApp(MaterialApp.router(
    routerConfig: goRouter,
  ));
}

关键点说明

  • redirect 逻辑:在每次路由跳转前触发,返回 null 允许导航,返回路径字符串则重定向。
  • 状态匹配:使用 state.matchedLocation 获取当前匹配的路由路径。
  • 动态监听:通过 refreshListenable 监听状态变化(如登录状态),自动触发重定向检查。

这种方法可实现登录验证、权限控制等常见导航守卫场景。

回到顶部