Authentication


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.

In this example, we'll combine the Login flow that we created in Declarative Routing with the router setup we have in Route Guards to create an app with basic authentication.
class App extends StatelessWidget {
    final _appRouter = AppRouter();

    
    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));
    }
}

Now, users will not be allowed to access the main app until they are logged in. And if they are not logged in, they are automatically brought to the login flow. No need for any route guards, no need to duplicate any login code - just a very simple state-based routing system!

And there you go - we now have a full-fledged app with:
  • Paths and redirects
  • Nested routes
  • Wrapped routes
  • Bottom navigation bar routing
  • Protected routes via Route Guard
  • Declarative Flow Routing for logging in
and more..

Thanks for checking out the AutoRoute tutorial!