how to set up RouteGuard in Flutter Modular for Firebase authentication

756 Views Asked by At

currently, the way to check if a user is logged in Flutter Fire as per the documentation (https://firebase.flutter.dev/docs/auth/usage#authentication-state):

FirebaseAuth.instance
  .authStateChanges()
  .listen((User? user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
    }
  });

the way to set up a route guard in Flutter Modular as per the documentation (https://modular.flutterando.com.br/docs/flutter_modular/navegation#route-guard)

class AuthGuard extends RouteGuard {
  AuthGuard() : super(redirectTo: '/login');

  @override
  Future<bool> canActivate(String path, ModularRoute router) {
    return Modular.get<AuthStore>().isLogged;
  }
}

how do I use this FlutterFire code to create the route guard in Flutter modular? I have trouble coming up with code that will return a Future from the FlutterFire auth code

1

There are 1 best solutions below

0
Álvaro Marcelo Kaim On

try use only this:

Future<bool> checkCurrentUser() async {
    return FirebaseAuth.instance.currentUser != null;
  }

Modular guard required one future of boolean.

 class AuthGuard extends RouteGuard {
  AuthGuard() : super(redirectTo: '/login/');

  @override
  Future<bool> canActivate(String path, ModularRoute route) async {
    
    return await Modular.get<AuthStore>().checkCurrentUser;
  }
}

resolve to me this.