Authentication is a staple of many apps, requiring users create an account and sign in before accessing specific pages. It may be first instinct to use a Guard
to handle authentication and protected routes, but AutoRoute makes this even easier to accomplish - all without route guards and minimal code.
class App extends StatelessWidget {
final _appRouter = AppRouter();
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerDelegate: AutoRouterDelegate.declarative(
_appRouter,
routes: (_) => [
// if the user is logged in, they may proceed to the main App
if (authService().isLoggedIn)
HomeRoute()
// if they are not logged in, bring them to the Login page
else
LoginWrapperRoute(onLogin: () => authService().logIn),
],
),
routeInformationParser:
_appRouter.defaultRouteParser(includePrefixMatches: true));
}
}