[AutoRoute] Using Route Guards or declarative routing for sign-in #67
InMatrix
started this conversation in
Routing API research
Replies: 1 comment 3 replies
-
Hey @InMatrix , it's definitely possible to do imperatively but I believe we did this declaratively because it's cleaner and more simple to understand. @Milad-Akarie to confirm. For example, by doing it declaratively all we need to do is: Widget build(BuildContext context) {
return MaterialApp.router(
routerDelegate: AutoRouterDelegate.declarative(
_appRouter,
routes: (_) => [
if (appState.isSignedIn)
AppStackRoute()
else
SignInRoute(
onSignedIn: _handleSignedIn,
),
],
),
routeInformationParser:
_appRouter.defaultRouteParser(includePrefixMatches: true));
} I think it's quite easy to understand that piece of code. If imperatively however, we need to make a bunch of changes. The above code snippet becomes simpler, but other parts of the code suffer: // the MaterialApp.router becomes simpler like so:
Widget build(BuildContext context) {
return MaterialApp.router(
routeInformationParser: _appRouter.defaultRouteParser(),
routerDelegate: _appRouter.delegate(),
);
} However, we need to make the following changes // create the guard
class AuthGuard extends AutoRouteGuard {
@override
void canNavigate(NavigationResolver resolver, StackRouter router) {
if (signedIn) {
resolver.next(true);
} else {
router.pushRoute(
SignInRoute(
onSignedIn: (credentials) => appState.signIn(credentials.username, credentials.password),
),
)
}
}
}
// add the guard
AutoRoute(
path: "/",
guards: [AuthGuard], // added line
page: AppStackScreen,
children: [
AutoRoute(path: "", page: HomeScreen),
AutoRoute(path: "books", page: BooksListScreen),
],
),
// and when appState.signOut() is called, we also manually have to push the signed out route
// whereas declaratively, you only need to call appState.signOut()
ElevatedButton(
onPressed: () {
appState.signOut();
context.router.replaceAll([ // this replaceAll is not needed in declarative snippet
SignInRoute(
onSignedIn: (credentials) => appState.signIn(
credentials.username, credentials.password))
]);
},
child: Text('Sign out'),
), I think that's it - @Milad-Akarie -sama to confirm |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
@theweiweiway @Milad-Akarie Cc: @chunhtai
AutoRoute's implementation of the sign-in routing scenario (snippet) uses declarative routing, but the scenario can probably also be implemented using Route Guards. I'm curious about any reasons for using one method over another. Thanks!
Beta Was this translation helpful? Give feedback.
All reactions