1
0
mirror of https://github.com/flutter/samples.git synced 2026-04-04 18:51:05 +00:00

navigation_and_routing: a bunch of cleanup (#886)

Fail early on nullable context objects - no code paths allow null
Eliminate superfluous private function
Use a function over an abstract class with one method
This commit is contained in:
Kevin Moore
2021-08-26 16:14:29 -07:00
committed by GitHub
parent ad6dc454f2
commit ecf716dcab
13 changed files with 84 additions and 122 deletions

View File

@@ -8,18 +8,12 @@ import 'package:path_to_regexp/path_to_regexp.dart';
import 'parsed_route.dart';
/// Used by [TemplateRouteParser] to guard access to routes.
///
/// Override this class to change the route that is returned by
/// [TemplateRouteParser.parseRouteInformation] if a condition is not met, for
/// example, if the user is not signed in.
abstract class RouteGuard<T> {
Future<T> redirect(T from);
}
typedef RouteGuard<T> = Future<T> Function(T from);
/// Parses the URI path into a [ParsedRoute].
class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
final List<String> _pathTemplates = [];
RouteGuard<ParsedRoute>? guard;
final List<String> _pathTemplates;
final RouteGuard<ParsedRoute>? guard;
final ParsedRoute initialRoute;
TemplateRouteParser({
@@ -27,27 +21,20 @@ class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
required List<String> allowedPaths,
/// The initial route
String? initialRoute = '/',
String initialRoute = '/',
/// [RouteGuard] used to redirect.
this.guard,
}) : initialRoute =
ParsedRoute(initialRoute ?? '/', initialRoute ?? '/', {}, {}) {
for (var template in allowedPaths) {
_addRoute(template);
}
}
void _addRoute(String pathTemplate) {
_pathTemplates.add(pathTemplate);
}
}) : initialRoute = ParsedRoute(initialRoute, initialRoute, {}, {}),
_pathTemplates = [
...allowedPaths,
],
assert(allowedPaths.contains(initialRoute));
@override
Future<ParsedRoute> parseRouteInformation(
RouteInformation routeInformation) async =>
await _parse(routeInformation);
Future<ParsedRoute> _parse(RouteInformation routeInformation) async {
RouteInformation routeInformation,
) async {
final path = routeInformation.location!;
final queryParams = Uri.parse(path).queryParameters;
var parsedRoute = initialRoute;
@@ -66,7 +53,7 @@ class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
// Redirect if a guard is present
var guard = this.guard;
if (guard != null) {
return guard.redirect(parsedRoute);
return guard(parsedRoute);
}
return parsedRoute;

View File

@@ -44,6 +44,6 @@ class RouteStateScope extends InheritedNotifier<RouteState> {
Key? key,
}) : super(key: key, notifier: notifier, child: child);
static RouteState? of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<RouteStateScope>()?.notifier;
static RouteState of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<RouteStateScope>()!.notifier!;
}