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

Flutter中GoRouter无法识别无尾斜杠的根路径深度链接

问题场景

Flutter应用使用GoRouter v13.2.1实现深度链接导航,Web端基于Next.js部署在Vercel,自定义域名www.example.com。已完成官方要求的深度链接配置:

  • 在/public/.well-known目录添加assetlinks.json
  • AndroidManifest.xml配置如下:
<meta-data android:name="flutter_deeplinking_enabled" 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" />
    <data android:scheme="http" android:host="www.example.com" />
    <data android:scheme="https" />
</intent-filter>

深度链接可从其他应用正常打开App,但集成GoRouter后出现路由匹配问题:

  • 访问www.example.com/details可正常跳转到详情页
  • 访问www.example.com或www.example.com/触发GoException: no routes for location: https://www.example.com

GoRouter接收的根路径为空字符串而非/,异常时路由状态:

state.error: null
state.path: null
state.fullPath:
state.uri: https://www.example.com
state.topRoute: null
state.extra: null
state.matchedLocation:
state.pageKey: [<'topLevel'>]
state.pathParameters: {}
state.name: null

特殊情况:访问www.example.com//(双斜杠)可正确匹配根路由。

原因分析

这是GoRouter v13.x版本处理根路径URI时的兼容问题:当URI路径为空(对应www.example.com)或仅含单个斜杠时,GoRouter未能正确将其映射到根路由/;而双斜杠被解析为/,因此能匹配成功。同时Vercel/Next.js的静态资源转发逻辑未对根路径的斜杠做强制补充,导致传递给Flutter的路径为空。

解决方案

方案1:通过GoRouter的redirect处理空路径

在GoRouter初始化时添加redirect逻辑,将空路径或单斜杠路径重定向到根路由/:

final router = GoRouter(
  redirect: (context, state) {
    // 处理空路径或仅斜杠的情况
    if (state.fullPath == '' || state.fullPath == '/') {
      return '/';
    }
    return null; // 其他路径正常处理
  },
  routes: [
    GoRoute(
      path: '/',
      builder: (_, __) => Scaffold(appBar: AppBar(title: const Text('Home Screen'))),
      routes: [
        GoRoute(
          path: 'details',
          builder: (_, __) => Scaffold(appBar: AppBar(title: const Text('Details Screen'))),
        ),
      ],
    ),
  ],
);

方案2:调整Vercel/Next.js配置,强制根路径带斜杠

在Next.js的next.config.js中配置重写规则,将根路径请求重定向到带斜杠的版本:

/** @type {import('next').NextConfig} */
const nextConfig = {
  async rewrites() {
    return [
      {
        source: '',
        destination: '/',
        permanent: true,
      },
    ];
  },
};

module.exports = nextConfig;

同时在Vercel项目设置中启用"Trailing Slash"选项,确保路径末尾自动添加斜杠。

方案3:升级GoRouter版本

GoRouter v14+及后续稳定版已修复部分根路径匹配问题,升级到最新版本可直接解决该兼容问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 16:12:38