matchRoute method

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

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);
  }

  final treeBranch = cumulativePaths
      .map((e) => MapEntry(e, _findRoute(e)))
      .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
    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);
    return RouteDecoder(
      mappedTreeBranch,
      arguments,
    );
  }

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

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