matchRoute method

RouteDecoder matchRoute(
  1. String name, {
  2. PageSettings? arguments,
})

从整个路由数中筛选出匹配的路由子树 返回一个 RouteDecoder 对象, 其中包含所有匹配的路由子树和参数信息。

final result = matchRoute('/home/products/1711205037025');
print(split); // WhereIterable<String> ((home, products, 1711205142604))
print(cumulativePaths); // ['/', 'home', 'products', '1711205037025']
print(treeBranch); // [{'/': GetPage()}, {'home': GetPage()}, {'home/products': : GetPage()}, {'/home/products/1711205142604':GetPage(),}]

Implementation

RouteDecoder matchRoute(String name, {PageSettings? arguments}) {
  final uri = Uri.parse(name);
  // 根据 '/' 分割字符串,并过滤掉空字符串
  final split = uri.path.split('/').where((element) => element.isNotEmpty);
  // 存储从根路径开始逐步累积的所有可能的路径
  var curPath = '/';
  final cumulativePaths = <String>['/'];
  for (var item in split) {
    if (curPath.endsWith('/')) {
      curPath += item;
    } else {
      curPath += '/$item';
    }
    cumulativePaths.add(curPath);
  }

  // 使用 cumulativePaths 中的每个路径尝试找到匹配的路由,如果找到,则将其及其关联的信息(如路径、参数等)存储在 treeBranch 中。
  final treeBranch = cumulativePaths
      .map((e) => MapEntry(e, _findRoute(e)))
      // 移除未找到的 key
      .where((element) => element.value != null)

      // Prevent page be disposed
      // 防止页面被销毁
      .map((e) => MapEntry(e.key, e.value!.copyWith(key: ValueKey(e.key))))
      .toList();

  // 解析路径参数(如果有)并将它们与查询参数合并。
  final params = Map<String, String>.from(uri.queryParameters);
  if (treeBranch.isNotEmpty) {
    // route is found, do further parsing to get nested query params
    // 找到路由,进行进一步解析以获取嵌套的 query params
    final lastRoute = treeBranch.last;
    // 解析路径参数
    final parsedParams = _parseParams(name, lastRoute.value.path);
    if (parsedParams.isNotEmpty) {
      params.addAll(parsedParams);
    }
    // copy parameters to all pages.
    // 将参数复制到所有页面。
    final mappedTreeBranch = treeBranch
        .map(
          (e) => e.value.copyWith(
            parameters: {
              if (e.value.parameters != null) ...e.value.parameters!,
              ...params,
            },
            name: e.key,
          ),
        )
        .toList();
    arguments?.params.clear();
    arguments?.params.addAll(params);
    // 如果找到匹配的路由,返回一个 RouteDecoder 对象,其中包含所有匹配的路由子树和参数信息。
    return RouteDecoder(
      mappedTreeBranch,
      arguments,
    );
  }

  arguments?.params.clear();
  arguments?.params.addAll(params);

  // route not found
  // 如果没有找到匹配的路由,返回一个包含空路由信息的 [RouteDecoder] 对象。
  return RouteDecoder(
    treeBranch.map((e) => e.value).toList(),
    arguments,
  );
}