Protect routes and build each route depending on a Stream

Viewed 133

Something that should be easy for me to understand has turned into a nightmare in the last days. I am using Firebase Auth to authenticate a user and using the Stream FirebaseAuth.instance.onAuthStateChanged to identify if the user is logged in. For this implement StreamProvider above in the main. Now the routes do not understand how they work, I am supposed to generate initialRoute dynamically, but this only runs the first time. How can I protect all the routes of my application, if they must first log in to enter. Let's go here with some code.

void main() {
  runApp(
    Provider<AuthService>(
      create: (_) => AuthService(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final user = context.watch<User>();
    return MaterialApp(
      title: 'Fruver Admin',
      debugShowCheckedModeBanner: false,
      theme: AppTheme.light,
      // does this only run once? what happens when you change? why not re-initialize? 
      initialRoute: user == null ? '/login' : '/',
      // I have thought of another alternative that if it works and it is with home:
      // home: user == null ? HomeScreen() : LoginScreen(),
      onGenerateRoute: (RouteSettings settings) {
        switch (settings.name) {
          case '/':
            // Need protect this route.
            return MaterialPageRoute(builder: (_) => HomeScreen());
          case '/login':
            return MaterialPageRoute(builder: (_) => LoginScreen());
          // other private routes here....
          // // Need protect this route.
          default:
            return MaterialPageRoute(builder: (_) {
              return Scaffold(
                body: Center(
                  child: Text('No route defined for ${settings.name}'),
                ),
              );
            });
        }
      },
    );
  }
}

// Why doesn't the current route to which initial Route initialized appear?
// RouteSettings("/login", null) It should be the result, right?
MaterialPageRoute<dynamic>(RouteSettings("null", null), animation: AnimationController#88993(⏭ 1.000; paused; for MaterialPageRoute<dynamic>(null)))
0 Answers
Related