Flutter GoRouter双斜杠Deeplink路由匹配异常问题求助
解决GoRouter中双斜杠Deeplink路由匹配失败的问题
问题原因
使用appschema://a这类双斜杠格式的Deeplink时,GoRouter会把a解析为URI的host部分,路径部分默认是/,所以会触发GoException: no routes for location: /错误;而单斜杠格式appschema:/a会被直接解析为路径/a,能正常匹配路由。
解决方案
方案1:通过GoRouter的redirect逻辑重定向
在GoRouter初始化时添加redirect回调,识别host对应的路径并进行重定向,适配双斜杠格式的Deeplink:
final _router = GoRouter( navigatorKey: _rootNavigatorKey, initialLocation: "/a", // 新增重定向逻辑 redirect: (context, state) { // 当双斜杠Deeplink进入时,location为"/"但host不为空 if (state.location == "/" && state.uri.host.isNotEmpty) { // 拼接host和path,适配带子路径的Deeplink(如appschema://a/details) return "/${state.uri.host}${state.uri.path}"; } return null; // 无需重定向时返回null }, routes: [ // 原有路由代码保持不变 ShellRoute( navigatorKey: _shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return MainTabBarScreen(child: child); }, routes: [ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return FirstScreen(); }, routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) { return FirstDetailScreen(); }, ), ], ), GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { return SecondScreen(articleId: 3); }, routes: <RouteBase>[ GoRoute( path: 'details2', parentNavigatorKey: _rootNavigatorKey, builder: (BuildContext context, GoRouterState state) { return SecondScreen(articleId: 4); }, ), ], ), ], ) ], );
方案2:自定义URI解析器(复杂场景)
如果需要更灵活的URI解析规则,可以自定义GoRouter的uriParser参数,实现自己的URI到路径的转换逻辑:
final _router = GoRouter( navigatorKey: _rootNavigatorKey, initialLocation: "/a", uriParser: UriParser( (uri) { // 自定义解析逻辑:如果host不为空,将host作为路径前缀 if (uri.host.isNotEmpty) { return Uri( path: "/${uri.host}${uri.path}", queryParameters: uri.queryParameters, ); } return uri; }, ), routes: [/* 原有路由 */], );
补充说明
- 方案1是最简洁的适配方式,能覆盖大部分场景,包括带子路径的双斜杠Deeplink(如
appschema://a/details) - 若原生端(如iOS)已经习惯使用双斜杠格式,无需修改原生代码,仅通过Flutter层的GoRouter配置即可解决问题
内容的提问来源于stack exchange,提问作者davidev
相关产品推荐
相关产品推荐

