Route Guards in Flutter

I was stumbling over this problem too and ended up using a FutureBuilder for this. Have a look at my routes:

final routes = {
  "https://stackoverflow.com/": (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.

Leave a Comment

error code: 521