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 4 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 @override
void initState() { void initState() {
final guard = BookstoreRouteGuard(auth: _auth);
/// Configure the parser with all of the app's allowed path templates. /// Configure the parser with all of the app's allowed path templates.
_routeParser = TemplateRouteParser( _routeParser = TemplateRouteParser(
allowedPaths: [ allowedPaths: [
@ -62,7 +60,7 @@ class _BookstoreState extends State<Bookstore> {
'/book/:bookId', '/book/:bookId',
'/author/:authorId', '/author/:authorId',
], ],
guard: guard, guard: _guard,
initialRoute: '/signin', 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() { void _handleAuthStateChanged() {
if (!_auth.signedIn) { if (!_auth.signedIn) {
_routeState.go('/signin'); _routeState.go('/signin');

@ -2,5 +2,47 @@
// for details. All rights reserved. Use of this source code is governed by a // 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. // BSD-style license that can be found in the LICENSE file.
export 'auth/auth.dart'; import 'package:flutter/foundation.dart';
export 'auth/auth_guard.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'; import 'parsed_route.dart';
/// Used by [TemplateRouteParser] to guard access to routes. /// Used by [TemplateRouteParser] to guard access to routes.
/// typedef RouteGuard<T> = Future<T> Function(T from);
/// 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);
}
/// Parses the URI path into a [ParsedRoute]. /// Parses the URI path into a [ParsedRoute].
class TemplateRouteParser extends RouteInformationParser<ParsedRoute> { class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
final List<String> _pathTemplates = []; final List<String> _pathTemplates;
RouteGuard<ParsedRoute>? guard; final RouteGuard<ParsedRoute>? guard;
final ParsedRoute initialRoute; final ParsedRoute initialRoute;
TemplateRouteParser({ TemplateRouteParser({
@ -27,27 +21,20 @@ class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
required List<String> allowedPaths, required List<String> allowedPaths,
/// The initial route /// The initial route
String? initialRoute = '/', String initialRoute = '/',
/// [RouteGuard] used to redirect. /// [RouteGuard] used to redirect.
this.guard, this.guard,
}) : initialRoute = }) : initialRoute = ParsedRoute(initialRoute, initialRoute, {}, {}),
ParsedRoute(initialRoute ?? '/', initialRoute ?? '/', {}, {}) { _pathTemplates = [
for (var template in allowedPaths) { ...allowedPaths,
_addRoute(template); ],
} assert(allowedPaths.contains(initialRoute));
}
void _addRoute(String pathTemplate) {
_pathTemplates.add(pathTemplate);
}
@override @override
Future<ParsedRoute> parseRouteInformation( Future<ParsedRoute> parseRouteInformation(
RouteInformation routeInformation) async => RouteInformation routeInformation,
await _parse(routeInformation); ) async {
Future<ParsedRoute> _parse(RouteInformation routeInformation) async {
final path = routeInformation.location!; final path = routeInformation.location!;
final queryParams = Uri.parse(path).queryParameters; final queryParams = Uri.parse(path).queryParameters;
var parsedRoute = initialRoute; var parsedRoute = initialRoute;
@ -66,7 +53,7 @@ class TemplateRouteParser extends RouteInformationParser<ParsedRoute> {
// Redirect if a guard is present // Redirect if a guard is present
var guard = this.guard; var guard = this.guard;
if (guard != null) { if (guard != null) {
return guard.redirect(parsedRoute); return guard(parsedRoute);
} }
return parsedRoute; return parsedRoute;

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

@ -28,7 +28,7 @@ class AuthorDetailsScreen extends StatelessWidget {
child: BookList( child: BookList(
books: author.books, books: author.books,
onTap: (book) { 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( body: AuthorList(
authors: LibraryScope.of(context).allAuthors, authors: LibraryScope.of(context).allAuthors,
onTap: (author) { 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) { void _handleBookTapped(Book book) {
_routeState.go('/book/${book.id}'); _routeState.go('/book/${book.id}');

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

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

@ -21,7 +21,7 @@ class BookstoreScaffoldBody extends StatelessWidget {
@override @override
Widget build(BuildContext context) { 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 // A nested Router isn't necessary because the back button behavior doesn't
// need to be customized. // need to be customized.

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

Loading…
Cancel
Save