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

GoRouter深度链接异常:从浏览器跳转至应用未触发路由

解决方案:Flutter iOS深度链接唤起后路由未触发问题

以下是针对你遇到的深度链接唤起应用但路由未触发问题的具体解决步骤:


1. 手动处理App唤醒时的深度链接

当应用从后台被深度链接唤起时,GoRouter不会自动触发路由跳转,需要手动监听应用生命周期并解析链接:

在根Widget中添加WidgetsBindingObserver,监听应用状态变化并处理链接:

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 应用启动时先处理初始链接
    _handleDeepLink(Uri.base);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 应用从后台回到前台时重新处理链接
    if (state == AppLifecycleState.resumed) {
      _handleDeepLink(Uri.base);
    }
  }

  void _handleDeepLink(Uri uri) {
    if (uri.scheme == 'my_invented_scheme' && uri.host == 'mydomain') {
      // 触发GoRouter跳转至对应路由
      GoRouter.of(context).go(uri.path);
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerConfig: _router,
    );
  }
}

2. 修正GoRouter初始路由配置

确保GoRouter初始化时能获取到启动时的深度链接路径,将initialLocation动态设置为当前Uri的路径:

final _router = GoRouter(
  initialLocation: Uri.base.path.isNotEmpty ? Uri.base.path : '/',
  routes: [
    GoRoute(
      path: '/login/:token',
      builder: (context, state) {
        final token = state.params['token'];
        if (token != null) {
          setLoginToken(token);
        }
        return const Home();
      },
    ),
    // 其他路由配置...
  ],
);

3. 检查深度链接的URL编码

确认后端生成的重定向链接中,JWT Token部分已做URL编码。如果Token包含/、?等特殊字符(标准JWT用Base64URL编码不会出现,但需验证后端实现),必须编码为%2F、%3F等格式,避免GoRouter解析路由时参数被截断。

4. 验证iOS Info.plist配置细节

调整Info.plist的关键配置项,确保深度链接能被正确识别:

  • 保留FlutterDeepLinkingEnabled为<true/>,这是Flutter处理深度链接的必要开关
  • 将CFBundleTypeRole从Editor改为Viewer,部分场景下该配置会影响链接唤起逻辑
  • 确认CFBundleURLSchemes中的my_invented_scheme拼写完全一致(大小写敏感)

修正后的Info.plist片段:

<key>FlutterDeepLinkingEnabled</key>
<true/>
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Viewer</string>
        <key>CFBundleURLName</key>
        <string>mydomain</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>my_invented_scheme</string>
        </array>
    </dict>
</array>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:57:42