matchRoute method
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();
// ── Slug / vanity-URL fix ──────────────────────────────────────────
// When the URL has segments beyond "/" (e.g. "/serzenmontoya") but
// only a parent segment like "/" matched, the full URL is NOT a
// registered route. Return an empty tree so unknownRoute triggers
// (which resolves vanity slugs via SlugResolverPage).
if (treeBranch.isNotEmpty && cumulativePaths.length > 1) {
final lastMatchedPath = treeBranch.last.key;
final lastCumulativePath = cumulativePaths.last;
if (lastMatchedPath != lastCumulativePath) {
// Only a parent matched — the full URL is unknown.
final params = Map<String, String>.from(uri.queryParameters);
arguments?.params.clear();
arguments?.params.addAll(params);
return RouteDecoder([], arguments);
}
}
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,
);
}