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
pull/887/head
Kevin Moore 3 years ago committed by GitHub
parent ad6dc454f2
commit ecf716dcab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -48,8 +48,6 @@ class _BookstoreState extends State<Bookstore> {
@override
void initState() {
final guard = BookstoreRouteGuard(auth: _auth);
/// Configure the parser with all of the app's allowed path templates.
_routeParser = TemplateRouteParser(
allowedPaths: [
@ -62,7 +60,7 @@ class _BookstoreState extends State<Bookstore> {
'/book/:bookId',
'/author/:authorId',
],
guard: guard,
guard: _guard,
initialRoute: '/signin',
);
@ -97,6 +95,21 @@ class _BookstoreState extends State<Bookstore> {
),
);
Future<ParsedRoute> _guard(ParsedRoute from) async {
final signedIn = _auth.signedIn;
final signInRoute = ParsedRoute('/signin', '/signin', {}, {});
// Go to /signin if the user is not signed in
if (!signedIn && from != signInRoute) {
return signInRoute;
}
// Go to /books if the user is signed in and tries to go to /signin.
else if (signedIn && from == signInRoute) {
return ParsedRoute('/books/popular', '/books/popular', {}, {});
}
return from;
}
void _handleAuthStateChanged() {
if (!_auth.signedIn) {
_routeState.go('/signin');

@ -2,5 +2,47 @@
// 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.
export 'auth/auth.dart';
export 'auth/auth_guard.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
/// A mock authentication service
class BookstoreAuth extends ChangeNotifier {
bool _signedIn = false;
bool get signedIn => _signedIn;
Future<void> signOut() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign out.
_signedIn = false;
notifyListeners();
}
Future<bool> signIn(String username, String password) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign in. Allow any password.
_signedIn = true;
notifyListeners();
return _signedIn;
}
@override
bool operator ==(Object other) =>
other is BookstoreAuth && other._signedIn == _signedIn;
@override
int get hashCode => _signedIn.hashCode;
}
class BookstoreAuthScope extends InheritedNotifier<BookstoreAuth> {
const BookstoreAuthScope({
required BookstoreAuth notifier,
required Widget child,
Key? key,
}) : super(key: key, notifier: notifier, child: child);
static BookstoreAuth of(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<BookstoreAuthScope>()!
.notifier!;
}

@ -1,48 +0,0 @@
// 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/foundation.dart';
import 'package:flutter/widgets.dart';
/// A mock authentication service
class BookstoreAuth extends ChangeNotifier {
bool _signedIn = false;
bool get signedIn => _signedIn;
Future<void> signOut() async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign out.
_signedIn = false;
notifyListeners();
}
Future<bool> signIn(String username, String password) async {
await Future<void>.delayed(const Duration(milliseconds: 200));
// Sign in. Allow any password.
_signedIn = true;
notifyListeners();
return _signedIn;
}
@override
bool operator ==(Object other) =>
other is BookstoreAuth && other._signedIn == _signedIn;
@override
int get hashCode => _signedIn.hashCode;
}
class BookstoreAuthScope extends InheritedNotifier<BookstoreAuth> {
const BookstoreAuthScope({
required BookstoreAuth notifier,
required Widget child,
Key? key,
}) : super(key: key, notifier: notifier, child: child);
static BookstoreAuth? of(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<BookstoreAuthScope>()
?.notifier;
}

@ -1,32 +0,0 @@
// 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 '../routing.dart';
import 'auth.dart';
/// An implementation of [RouteGuard] that redirects to /signIn
class BookstoreRouteGuard implements RouteGuard<ParsedRoute> {
final BookstoreAuth auth;
BookstoreRouteGuard({
required this.auth,
});
/// Redirect to /signin if the user isn't signed in.
@override
Future<ParsedRoute> redirect(ParsedRoute from) async {
final signedIn = auth.signedIn;
final signInRoute = ParsedRoute('/signin', '/signin', {}, {});
// Go to /signin if the user is not signed in
if (!signedIn && from != signInRoute) {
return signInRoute;
}
// Go to /books if the user is signed in and tries to go to /signin.
else if (signedIn && from == signInRoute) {
return ParsedRoute('/books/popular', '/books/popular', {}, {});
}
return from;
}
}

@ -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;

@ -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!;
}

@ -28,7 +28,7 @@ class AuthorDetailsScreen extends StatelessWidget {
child: BookList(
books: author.books,
onTap: (book) {
RouteStateScope.of(context)!.go('/book/${book.id}');
RouteStateScope.of(context).go('/book/${book.id}');
},
),
),

@ -21,7 +21,7 @@ class AuthorsScreen extends StatelessWidget {
body: AuthorList(
authors: LibraryScope.of(context).allAuthors,
onTap: (author) {
RouteStateScope.of(context)!.go('/author/${author.id}');
RouteStateScope.of(context).go('/author/${author.id}');
},
),
);

@ -93,7 +93,7 @@ class _BooksScreenState extends State<BooksScreen>
);
}
RouteState get _routeState => RouteStateScope.of(context)!;
RouteState get _routeState => RouteStateScope.of(context);
void _handleBookTapped(Book book) {
_routeState.go('/book/${book.id}');

@ -37,8 +37,8 @@ class _BookstoreNavigatorState extends State<BookstoreNavigator> {
@override
Widget build(BuildContext context) {
final routeState = RouteStateScope.of(context)!;
final authState = BookstoreAuthScope.of(context)!;
final routeState = RouteStateScope.of(context);
final authState = BookstoreAuthScope.of(context);
final pathTemplate = routeState.route.pathTemplate;
final library = LibraryScope.of(context);

@ -15,7 +15,7 @@ class BookstoreScaffold extends StatelessWidget {
@override
Widget build(BuildContext context) {
final routeState = RouteStateScope.of(context)!;
final routeState = RouteStateScope.of(context);
final selectedIndex = _getSelectedIndex(routeState.route.pathTemplate);
return Scaffold(

@ -21,7 +21,7 @@ class BookstoreScaffoldBody extends StatelessWidget {
@override
Widget build(BuildContext context) {
var currentRoute = RouteStateScope.of(context)!.route;
var currentRoute = RouteStateScope.of(context).route;
// A nested Router isn't necessary because the back button behavior doesn't
// need to be customized.

@ -5,7 +5,7 @@
import 'package:flutter/material.dart';
import 'package:url_launcher/link.dart';
import '../auth/auth.dart';
import '../auth.dart';
import '../routing.dart';
class SettingsScreen extends StatefulWidget {
@ -52,7 +52,7 @@ class SettingsContent extends StatelessWidget {
),
ElevatedButton(
onPressed: () {
BookstoreAuthScope.of(context)!.signOut();
BookstoreAuthScope.of(context).signOut();
},
child: const Text('Sign out'),
),
@ -66,7 +66,7 @@ class SettingsContent extends StatelessWidget {
TextButton(
child: const Text('Go directly to /book/0 (RouteState)'),
onPressed: () {
RouteStateScope.of(context)!.go('/book/0');
RouteStateScope.of(context).go('/book/0');
},
),
].map((w) => Padding(padding: const EdgeInsets.all(8), child: w)),

Loading…
Cancel
Save