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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With