Flutter
Routing
Redirect between the splash, sign-in and app routes with any router.
AuthStateListenable exposes the auth state as a ValueListenable. Routers that accept a Listenable re-run their redirect when it changes. There is no dependency on a particular router.
go_router
final auth = AuthStateListenable(authyra);
final router = GoRouter(
refreshListenable: auth,
redirect: (context, state) {
final atSignIn = state.matchedLocation == '/sign-in';
return switch (auth.value) {
AuthUnknown() => '/splash',
AuthSignedOut() => atSignIn ? null : '/sign-in',
AuthSignedIn() => atSignIn ? '/' : null,
};
},
routes: [
GoRoute(path: '/splash', builder: (_, _) => const SplashScreen()),
GoRoute(path: '/sign-in', builder: (_, _) => const SignInScreen()),
GoRoute(path: '/', builder: (_, _) => const HomeScreen()),
],
);
Call auth.dispose() when the router goes away.
Keeping the destination
To send users back where they were after signing in, put the location in the redirect:
AuthSignedOut() => atSignIn
? null
: '/sign-in?from=${Uri.encodeComponent(state.uri.toString())}',
and read from once signIn completes.
Other routers
Any router with a refresh hook works the same way: listen to AuthStateListenable, or to authyra.states directly, and compute the route from the current state.