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

如何将这段Flutter代码转换为Go_Route实现相同功能?

结合GoRouter与Riverpod实现用户状态路由重定向

原Riverpod实现代码

ref.watch(currentUserAccountProvider).when(
  data: (user) {
    if (user != null) {
      return const HomeView();
    }
    return const SignUpView();
  },
  error: (error, st) => ErrorPage(
    error: error.toString(),
  ),
  loading: () => const LoadingPage(),
);

转换为GoRouter的实现方案

核心思路是将路由逻辑与Riverpod状态监听绑定,通过GoRouter的redirect机制实现自动跳转,同时把GoRouter实例托管在Riverpod Provider中,确保状态变化时路由逻辑自动更新。

1. 定义GoRouter Provider

final goRouterProvider = Provider<GoRouter>((ref) {
  // 监听用户状态的异步变化
  final userAsync = ref.watch(currentUserAccountProvider);

  return GoRouter(
    initialLocation: '/',
    redirect: (context, state) {
      // 处理加载状态:跳转到加载页
      if (userAsync.isLoading) {
        return '/loading';
      }

      // 处理错误状态:跳转到错误页并传递错误信息
      if (userAsync.hasError) {
        return '/error?message=${Uri.encodeComponent(userAsync.error.toString())}';
      }

      // 处理用户登录状态
      final user = userAsync.value;
      final currentLocation = state.location;

      // 用户已登录:确保跳转到首页,避免无限重定向
      if (user != null) {
        return currentLocation == '/home' ? null : '/home';
      }
      // 用户未登录:确保跳转到注册页
      else {
        return currentLocation == '/signup' ? null : '/signup';
      }
    },
    routes: [
      GoRoute(
        path: '/home',
        builder: (_, __) => const HomeView(),
      ),
      GoRoute(
        path: '/signup',
        builder: (_, __) => const SignUpView(),
      ),
      GoRoute(
        path: '/loading',
        builder: (_, __) => const LoadingPage(),
      ),
      GoRoute(
        path: '/error',
        builder: (context, state) {
          final errorMsg = state.queryParams['message'] ?? '未知错误';
          return ErrorPage(error: errorMsg);
        },
      ),
    ],
  );
});

2. 在App中使用该Router

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final router = ref.watch(goRouterProvider);
    return MaterialApp.router(
      routerConfig: router,
    );
  }
}

关键说明

  • 将GoRouter放入Riverpod Provider中,能自动监听currentUserAccountProvider的状态变化,状态更新时GoRouter会重建并重新执行redirect逻辑,无需手动监听。
  • redirect函数中通过判断当前路由位置避免无限重定向(返回null表示不跳转)。
  • 错误信息通过URL参数传递,确保错误页能获取到具体错误内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 16:35:16