Flutter Web Firebase Auth user is logged out after refresh

Viewed 159

I have a Flutter Web App where the user is logged in via Firebase. The Problem is that every time the page is refreshed, the user is logged out.

Similiar for iOS: User stays logged in after refresh but is being logged out when completely closing the app.

I know there is this issue which says that it should be fixed with the latest version, but I am already on the supposedly fixed version:

firebase_core: ^1.20.0

firebase_auth: ^3.6.0

cloud_firestore: ^3.4.1

I am using the go_router and redirect the user if he is not logged in:

final GoRouter router = GoRouter(
  key: Get.key,
  urlPathStrategy: UrlPathStrategy.path,
  redirect: (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;
  },
  ...

And this is my AuthService.isLoggedIn():

  static final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

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

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

What am I missing here? It says everywhere that it should be fixed but it's not working for me.. Let me know if you need any more details!

3 Answers

The one way to achieve that is you have to put a check and stored that value as a persistent data.

So you can use Shared Preferences and when the user login for the first time change the value of shared preference to true.

And then in initstate of login page get the value of shared preference and check if it is true or not. If true navigate to homepage otherwise to login page.

Note : this approach may not work in localhost but I m sure this will work when you host it to firebase hosting.

Hope this will help.

Isn't that Redundant? Why not just return currentUser?

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

Update to dependencies: firebase_auth: ^3.6.4 This bug is now resolved in lastest version.

Use stream - FirebaseAuth.instance.authStateChanges()

FirebaseAuth.instance
  .authStateChanges()
  .listen((User? user) {
    if (user != null) {
      print(user.uid);
    }
  });
Related