Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route Guards in Flutter

Tags:

flutter

dart

In Angular, one can use the canActivate for route guarding.

In Flutter, how would one go about it? Where is the guard placed? How do you guard routes?

I'm thinking along the lines of this:

  • User logged in. Their token is stored in Shared Preference (the right way to store tokens? )
  • User closed the app.
  • User opens app again. As the application starts, it determines if user is logged in (perhaps a service that checks the storage for token), and then
  • If logged in, load the homepage route
  • If not logged in, load the login page
like image 753
KhoPhi Avatar asked Jun 25 '18 16:06

KhoPhi


People also ask

What is auto route Flutter?

What is AutoRoute? It's a Flutter navigation package, it allows for strongly-typed arguments passing, effortless deep-linking and it uses code generation to simplify routes setup, with that being said it requires a minimal amount of code to generate everything needed for navigation inside of your App.


1 Answers

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.

like image 162
MasseElch Avatar answered Oct 08 '22 19:10

MasseElch