Files
iroute/lib/13/go/raw_book/src/routing/parser.dart
toly e95c34018e 9
2023-09-22 09:15:11 +08:00

63 lines
2.0 KiB
Dart

// Copyright 2021, the Flutter project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:path_to_regexp/path_to_regexp.dart';
import 'parsed_route.dart';
/// Used by [TemplateRouteParser] to guard access to routes.
typedef RouteGuard<T> = Future<T> Function(T from);
/// Parses the URI path into a [ParsedRoute].
class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
final List<String> _pathTemplates;
final ParsedRoute initialRoute;
TemplateRouteParser({
/// The list of allowed path templates (['/', '/users/:id'])
required List<String> allowedPaths,
/// The initial route
String initialRoute = '/',
}) : initialRoute = ParsedRoute(initialRoute, initialRoute, {}, {}),
_pathTemplates = [
...allowedPaths,
],
assert(allowedPaths.contains(initialRoute));
@override
Future<ParsedRoute> parseRouteInformation(
RouteInformation routeInformation,
) async {
print("=======parseRouteInformation:${routeInformation.uri.path}===================");
final uri = routeInformation.uri;
final path = uri.toString();
final queryParams = uri.queryParameters;
var parsedRoute = initialRoute;
for (var pathTemplate in _pathTemplates) {
final parameters = <String>[];
var pathRegExp = pathToRegExp(pathTemplate, parameters: parameters);
if (pathRegExp.hasMatch(path)) {
final match = pathRegExp.matchAsPrefix(path);
if (match == null) continue;
final params = extract(parameters, match);
parsedRoute = ParsedRoute(path, pathTemplate, params, queryParams);
}
}
return parsedRoute;
}
@override
RouteInformation restoreRouteInformation(ParsedRoute configuration) {
print("=======restoreRouteInformation:${configuration}===================");
return RouteInformation(uri: Uri.parse(configuration.path));
}
}