parseRouteInformation method
Converts the given route information into parsed data to pass to a RouterDelegate.
The method should return a future which completes when the parsing is complete. The parsing may be asynchronous if, e.g., the parser needs to communicate with the OEM thread to obtain additional data about the route.
Consider using a SynchronousFuture if the result can be computed synchronously, so that the Router does not need to wait for the next microtask to pass the data to the RouterDelegate.
One can implement parseRouteInformationWithDependencies instead if the parsing depends on other dependencies from the BuildContext.
Implementation
@override
Future<RouteInformation> parseRouteInformation(
RouteInformation routeInformation,
) async {
var uri = routeInformation.uri;
var path = uri.path;
// 1. 处理路由别名
if (routeAliases != null && routeAliases!.containsKey(path)) {
final aliasPath = routeAliases![path]!;
uri = Uri.parse(aliasPath).replace(
queryParameters: uri.queryParameters.isNotEmpty
? uri.queryParameters
: null,
);
path = uri.path;
}
// 2. 解析路径参数
Map<String, String>? pathParams;
String? matchedPattern;
if (enablePathParams && patterns != null) {
for (var pattern in patterns!) {
pathParams = pattern.match(path);
if (pathParams != null) {
matchedPattern = pattern.pattern;
break;
}
}
}
// 3. 解析查询参数
Map<String, String>? queryParams;
if (enableQueryParams && uri.hasQuery) {
queryParams = Map<String, String>.from(uri.queryParameters);
}
// 4. 验证路由
if (enableValidation) {
final isValid = _validateRoute(uri, pathParams, queryParams);
if (!isValid && defaultRoute != null) {
uri = Uri.parse(defaultRoute!);
path = uri.path;
pathParams = null;
queryParams = null;
}
}
// 5. 构建新的 RouteInformation,将解析结果存储在 state 中
return RouteInformation(
uri: uri,
state: {
'path': path,
'pathParams': pathParams,
'queryParams': queryParams,
'matchedPattern': matchedPattern,
'originalUri': routeInformation.uri.toString(),
},
);
}