Route Guards in Flutter
I don't think there is a route guarding mechanism per se, but you can do logic in the main
function before loading the app, or use the onGenerateRoute
property of a MaterialApp
. One way to do that in your case is to await an asynchronous function that checks if the user is logged in before loading the initial route. Something like
main() {
fetchUser().then((user) {
if (user != null) runApp(MyApp(page: 'home'));
else runApp(MyApp(page: 'login'));
});
}
But you may also be interested in the way the Shrine app does it. They have the login page as the initial route in any case and remove it if the user is logged in. That way the user sees the login page until it has been determined whether or not they log in. I've included the relevant snippet below.
class ShrineApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shrine',
home: HomePage(),
initialRoute: '/login',
onGenerateRoute: _getRoute,
);
}
Route<dynamic> _getRoute(RouteSettings settings) {
if (settings.name != '/login') {
return null;
}
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => LoginPage(),
fullscreenDialog: true,
);
}
}
If you don't want them to see the login page at all if they are logged in, use the first approach and you can control the splash screen that shows before runApp
has a UI by exploring this answer.
I was stumbling over this problem too and ended up using a FutureBuilder
for this. Have a look at my routes:
final routes = {
'/': (BuildContext context) => FutureBuilder<AuthState>(
// This is my async call to sharedPrefs
future: AuthProvider.of(context).authState$.skipWhile((_) => _ == null).first,
builder: (BuildContext context, AsyncSnapshot<AuthState> snapshot) {
switch(snapshot.connectionState) {
case ConnectionState.done:
// When the future is done I show either the LoginScreen
// or the requested Screen depending on AuthState
return snapshot.data == AuthState.SIGNED_IN ? JobsScreen() : LoginScreen()
default:
// I return an empty Container as long as the Future is not resolved
return Container();
}
},
),
};
If you want to reuse the code across multiple routes you could extend the FutureBuilder.