You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Flutter Go Router深度链接异常:无法通过Action扩展或URL命令导航至嵌套路由

Flutter Go Router深度链接异常:无法通过Action扩展或URL命令导航至嵌套路由

嗨,我明白遇到这种深度链接跳不对页面的问题有多闹心,我帮你梳理下可能的问题点和解决方案:

首先,最明显的问题:路径不匹配!

看你的路由配置,嵌套路由的路径是/first/image-capture,但你测试用的所有命令里,路径都是/first/image(比如gorouterapp://com.bahadirarslan.goRouterDeeplink/first/image)——这完全对应不上啊!Go Router找不到匹配的路由,自然就默认跳回首页了。

其次,URL Scheme的结构需要调整

你的Info.plist里配置了CFBundleURLSchemesgorouterappCFBundleURLNamecom.bahadirarslan.goRouterDeeplink,正确的深度链接格式应该是两种:

  1. 带host的完整格式:gorouterapp://com.bahadirarslan.goRouterDeeplink/first/image-capture
  2. 省略host的简化格式(Go Router会直接解析path部分):gorouterapp:///first/image-capture(注意是三个斜杠)

你之前的测试命令要么路径错了,要么格式不对,比如gorouterapp:/first/image这种单斜杠的格式肯定是无效的。

另外,确保Go Router正确处理冷启动的深度链接

当App从外部(比如Action扩展、simctl命令)冷启动时,Go Router需要正确获取启动时的路由路径。你可以在初始化Go Router时,手动传入initialLocation,基于系统提供的默认路由名:

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

void main() {
  // 获取启动时的深度链接路径
  final initialLocation = WidgetsBinding.instance.platformDispatcher.defaultRouteName;
  runApp(MyApp(initialLocation: initialLocation));
}

class MyApp extends StatelessWidget {
  final String? initialLocation;

  const MyApp({super.key, this.initialLocation});

  @override
  Widget build(BuildContext context) {
    final _router = GoRouter(
      initialLocation: initialLocation == '/' ? null : initialLocation,
      redirect: (context, state) {
        print('Redirect triggered: ${state.location}'); // 现在应该能打印出正确的路径了
        return null;
      },
      routes: [
        GoRoute(
          path: '/',
          builder: (context, state) => const MyHomePage(),
        ),
        GoRoute(
          path: '/first',
          builder: (context, state) => const FirstScreen(),
          routes: [
            GoRoute(
              path: 'image-capture',
              builder: (context, state) => const ImageDart(),
            ),
          ],
        ),
      ],
    );

    return MaterialApp.router(
      routerConfig: _router,
      title: 'Go Router Deeplink Demo',
    );
  }
}

最后,修正你的测试命令

用正确的路径和格式测试,比如:

# 带host的格式
xcrun simctl openurl booted gorouterapp://com.bahadirarslan.goRouterDeeplink/first/image-capture

# 简化格式
xcrun simctl openurl booted gorouterapp:///first/image-capture

这样应该就能正确跳转到ImageDart页面了,同时你的redirect函数也会被触发打印日志。

另外,关于你提到的那个已关闭的Issue,它主要是修复了Go Router处理深度链接时的一些初始化逻辑问题,现在你按照上面的方法配置,应该就能正常工作了。

备注:内容来源于stack exchange,提问作者bahadir arslan

火山引擎 最新活动