0

previously I only used firebase authstate (StreamBuilder) by using initialroutes for routes my page

now I want to use go_route to redirect my page if FirebaseAuth not null

how can go_routes be able to detect the state of the authstatechange

this My Main.dart class

Widget build(BuildContext context) {
    return StreamBuilder<User?>(
        stream: authservice.authState,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            print(snapshot.data);
            return Sizer(builder: ((context, orientation, deviceType) {
              return MaterialApp.router(
                builder: (context, child) => ResponsiveWrapper.builder(child,
                    maxWidth: 1200,
                    minWidth: 480,
                    defaultScale: true,
                    breakpoints: [
                      const ResponsiveBreakpoint.resize(450, name: MOBILE),
                      const ResponsiveBreakpoint.autoScale(800, name: TABLET),
                      const ResponsiveBreakpoint.autoScale(1000, name: TABLET),
                      const ResponsiveBreakpoint.resize(1200, name: DESKTOP),
                      const ResponsiveBreakpoint.autoScale(2460, name: "4K"),
                    ],
                    background: Container(color: const Color(0xFFF5F5F5))),
                title: 'Welcome',
                theme: ThemeData(primaryColor: Colors.blueGrey),
                // initialRoute: snapshot.data != null ? "/dashboard" : "/intro",
                // routes: {
                //   '/': (context) => const Intro(),
                //   '/dashboard': (context) => const Dashboard(),
                //   '/login': (context) => const Login(),
                //   '/register': (context) => const Register()
                // },
                routerConfig: router,
              );
            }));
          }
          return const Loading();
        });
  }

this my go_route class

final GoRouter router = GoRouter(
    routes: routes,
    initialLocation: '/login',
    debugLogDiagnostics: true,
    routerNeglect: true);

List<RouteBase> routes = [
  GoRoute(
    path: '/login',
    name: 'login',
    builder: (context, state) => const Login(),
  ),
  GoRoute(
    path: '/register',
    name: 'register',
    builder: (context, state) => const Register(),
  ),
  GoRoute(
    path: '/intro',
    name: 'intro',
    builder: (context, state) => const Intro(),
  ),
  GoRoute(
    path: '/dashboard',
    name: 'dashboard',
    builder: (context, state) => const Dashboard(),
  ),
];

in my authservice class I just use

final FirebaseAuth _auth = FirebaseAuth.instance;

  Stream<User?> get authState => _auth.authStateChanges();

how can go_routes be able to detect the state of the authstatechange, in some sample projects no one is using go_routes with authstatechange from Firebase

1 Answers1

0

It's not a good practice to put the StreamBuilder around your MaterialApp Widget. By doing so, you build the actual App only after the FirebaseAuth receives data. Until that the app isn't initialized properly (you could also run into some problems with using go_router).

You should instead put your Loading-Widget inside your App Widget and (for example) set the initialroute of go_router to the Loading-Widget. There you can await the FirebaseAuth data. After receiving the login information you then navigate to the according route with go_router, depending on the login state. Alternatively, you could also put the logic into one Widget and render the content according to the FirebaseAuth state.

If you want to do more complex interactions with your FirebaseAuth or other Firebase data, I strongly recommend the use of some kind of state management package, for example Flutter Riverpod. Thereby you can access the auth state from everywhere in your app and better interact with it.

Michel
  • 206
  • 5
  • Thank You, in @Michel opition what the best method I should use? make authentication in loading widget or flutter riverpod, I want to make login and register page with **signInWithEmailAndPassword** and **Social Media Account** – Muzamil Haq Mar 22 '23 at 00:16
  • This depends on the features you want to implement in your app. If you need the authentication just to navigate the user to the according screen when he / she logs in, you can take the simpler solution and implement the logic inside a Loading Page or Wrapper Widget. If you're not sure yet, what you need in your app and you don't want to spend time learning Riverpod, I would recommend starting with this approach and later switch to a state management package if necessary. Otherwise you can check this video to get an overview of Riverpod and Firebase: https://www.youtube.com/watch?v=DVgjysZF82k. – Michel Mar 22 '23 at 13:07