matchRoute method

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

Implementation

RouteDecoder<T> matchRoute(String name, {PageSettings? arguments}) {
  final Uri uri = Uri.parse(name);
  final Iterable<String> split =
      uri.path.split("/").where((String element) => element.isNotEmpty);
  String curPath = "/";
  final List<String> cumulativePaths = <String>[
    "/",
  ];
  for (final String item in split) {
    if (curPath.endsWith("/")) {
      curPath += item;
    } else {
      curPath += "/$item";
    }
    cumulativePaths.add(curPath);
  }

  final List<MapEntry<String, GetPage<T>>> treeBranch = cumulativePaths
      .map((String e) => MapEntry<String, GetPage<T>?>(e, _findRoute(e)))
      .where((MapEntry<String, GetPage<T>?> element) => element.value != null)

      ///Prevent page be disposed
      .map(
        (MapEntry<String, GetPage<T>?> e) => MapEntry<String, GetPage<T>>(
          e.key,
          e.value!.copyWith(
            key: ValueKey<String>(e.key),
          ),
        ),
      )
      .toList();

  final Map<String, String> params =
      Map<String, String>.from(uri.queryParameters);
  if (treeBranch.isNotEmpty) {
    //route is found, do further parsing to get nested query params
    final MapEntry<String, GetPage<T>> lastRoute = treeBranch.last;
    final Map<String, String> parsedParams =
        _parseParams(name, lastRoute.value.path);
    if (parsedParams.isNotEmpty) {
      params.addAll(parsedParams);
    }
    //copy parameters to all pages.
    final List<GetPage<T>> mappedTreeBranch = treeBranch
        .map(
          (MapEntry<String, GetPage<T>> e) => e.value.copyWith(
            parameters: <String, String>{
              if (e.value.parameters != null) ...e.value.parameters!,
              ...params,
            },
            name: e.key,
          ),
        )
        .toList();
    arguments?.params.clear();
    arguments?.params.addAll(params);
    return RouteDecoder<T>(
      mappedTreeBranch,
      arguments,
    );
  }

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

  //route not found
  return RouteDecoder<T>(
    treeBranch.map((MapEntry<String, GetPage<T>> e) => e.value).toList(),
    arguments,
  );
}