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

Flutter GoRouter安卓深度链接无法跳转指定页面求助

解决GoRouter深度链接无法跳转指定页面的问题

核心问题分析

你遇到的问题本质是StreamBuilder重建MaterialApp.router时,GoRouter的路由信息被重置,加上Auth状态变化的干扰,导致深度链接的目标路径被覆盖回根路径。以下是具体解决步骤:


1. 重构Auth状态处理逻辑(替换StreamBuilder)

不要用StreamBuilder包裹MaterialApp.router,改用GoRouter内置的redirect和refreshListenable来处理Auth状态,这样能保留深度链接的路由信息:

第一步:配置带Auth监听的GoRouter

final router = GoRouter(
  routes: [
    GoRoute(
      path: '/',
      builder: (context, state) => const HomePage(),
    ),
    GoRoute(
      path: '/login',
      builder: (context, state) => const LoginPage(),
    ),
    GoRoute(
      path: '/profile',
      builder: (context, state) => const ProfilePage(),
    ),
  ],
  // 处理路由重定向逻辑
  redirect: (context, state) {
    final isLoggedIn = router.auth.currentUser != null;
    final targetPath = state.subloc;
    final isLoggingIn = targetPath == '/login';

    // 未登录且不在登录页:跳转到登录页,携带原路径作为参数
    if (!isLoggedIn && !isLoggingIn) {
      return '/login?redirect=$targetPath';
    }
    // 已登录且在登录页:跳回之前的目标路径(或首页)
    if (isLoggedIn && isLoggingIn) {
      return state.queryParams['redirect'] ?? '/';
    }
    // 其他情况保留原路径,不重定向
    return null;
  },
  // 监听Auth状态变化,触发重定向
  refreshListenable: AuthRefreshNotifier(router.auth),
);

// 自定义监听类,监听Auth状态变化
class AuthRefreshNotifier extends ChangeNotifier {
  AuthRefreshNotifier(FirebaseAuth auth) {
    auth.authStateChanges().listen((_) => notifyListeners());
  }
}

第二步:简化主页面代码

移除StreamBuilder,直接返回MaterialApp.router:

MaterialApp.router(
  title: 'Myservy: App de Servicios',
  theme: apptheme,
  routeInformationParser: router.routeInformationParser,
  routerDelegate: router.routerDelegate,
  routeInformationProvider: router.routeInformationProvider,
);

2. 优化AndroidManifest配置

调整intent-filter的data标签,确保http/https scheme配置正确:

<meta-data android:name="flutter_deeplinking_enable" android:value="true" />
<intent-filter android:autoVerify="true">
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <!-- 合并http/https的host配置,避免路径匹配问题 -->
  <data android:scheme="http" android:host="servlymaindev.web.app" />
  <data android:scheme="https" android:host="servlymaindev.web.app" />
</intent-filter>

3. 验证与调试

  • 冷启动测试:确保App处于完全关闭状态测试深度链接,后台运行的App可能不会重新处理路由信息
  • 打印路由日志:在GoRouter的redirect函数中添加日志,确认是否接收到正确的深度链接路径:
    redirect: (context, state) {
      print('接收的深度链接路径: ${state.subloc}');
      // ...其他逻辑
    }
    
  • 检查GoRouter版本:确保使用最新版GoRouter,旧版本可能存在深度链接处理的bug

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:24:55