skip to Main Content

I am using the go_router and Firebase Auth for my web application but can not properly set it up. I tried this:

class AuthService {
  static final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  static User? get currentUser => FirebaseAuth.instance.currentUser;

  static bool isLoggedIn() {
    return _firebaseAuth.currentUser != null;
  }
  ...

With my router:

  redirect: (context, state) {
    final String destination = state.location;

    final bool isOnStartView = destination == '/start';
    final bool isOnEmailFlow = state.subloc.contains('/email');

    if (!isOnStartView && !isOnEmailFlow && !AuthService.isLoggedIn()) {
      return '/start';
    }

    return null;
  },

However this is not working properly as isLoggedIn is always return false even if there a is a user logged in. I searched for this topic and found that I probably use some sort of Stream or Notifier with onAuthStateChange but I didn’t find anything on how to implement a proper FirebaseAuthentication Flow in combination with GoRouter.

How would I do that?

Let me know if you need any more info.

2

Answers


  1. You can do this

    class AuthService {
      static final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
    
      static User? get currentUser => FirebaseAuth.instance.currentUser;
    
      static bool? _isLoggedIn = null;
    
    
      static bool isLoggedIn() {
        if(_isLoggedIn == null) {
           FirebaseAuth.instance
              .authStateChanges()
              .listen((User? user) {
                 _isLoggedIn = user?.uid != null;
               });
           _isLoggedIn = _firebaseAuth.currentUser?.uid != null;
           return _isLoggedIn ?? false;
        }
        else {
           return _isLoggedIn ?? false;
        }
      ...
    
    Login or Signup to reply.
  2. You can use riverpod or provider to listen changes
    here is code sample

    import 'dart:developer';
    
    import 'package:flutter/material.dart';
    import 'package:flutter_riverpod/flutter_riverpod.dart';
    import 'package:go_router/go_router.dart';
    import 'package:testproject/Home%20Screen/home_screen.dart';
    import 'package:testproject/Model/user_model.dart';
    import 'package:testproject/Providers/UserProvider/user_data_provider.dart';
    import 'package:testproject/Screens/login_screen.dart';
    import 'package:testproject/Screens/sign_up.dart';
    import 'package:testproject/Service/auth_service.dart';
    
    import '../Providers/Satates/user_states.dart';
    import '../Providers/UserProvider/user_state_provider.dart';
    
    class MyRoutes extends ChangeNotifier {
      final Ref ref;
      MyRoutes(this.ref) {
        ref.listen<LoginState>(
            userStateprovider, (previous, next) => notifyListeners());
      }
    
      List<GoRoute> get _routes => [
            GoRoute(
              name: "Login",
              path: "/login",
              builder: (context, state) => SigninPage(),
            ),
            GoRoute(
              name: "Home",
              path: "/home",
              builder: (context, state) => const HomeScreen(),
            ),
            GoRoute(
              name: "Signup",
              path: "/signup",
              builder: (context, state) => const SignUpScreen(),
            ),
          ];
    
      String? _redirectLogic(GoRouterState state) {
        final loginState = ref.read(userStateprovider);
        final user = ref.read(userProvider.state);
        if (loginState is LoginStateInitial && auth.currentUser != null) {
          log("message");
          Future.delayed(const Duration(seconds: 0), () {
            user.state = UserModel(
                email: auth.currentUser!.email!, userid: auth.currentUser!.uid);
            ref.read(userStateprovider.notifier).newstate = LoginStateSuccess(
                UserModel(
                    email: auth.currentUser!.email!,
                    userid: auth.currentUser!.uid));
          });
        }
        log(state.location);
        log(auth.currentUser.toString());
        final areWeLoggingIn = state.location == '/home';
        log(areWeLoggingIn.toString());
        if (areWeLoggingIn) {
          return loginState is LoginStateSuccess ? null : "/login";
        }
    
        return null;
      }
    }
    
    final routeProvider = Provider<GoRouter>((ref) {
      final routeRef = MyRoutes(ref);
      return GoRouter(
          urlPathStrategy: UrlPathStrategy.path,
          initialLocation: "/login",
          refreshListenable: routeRef,
          redirect: routeRef._redirectLogic,
          routes: routeRef._routes);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search