Firebase Authentication is not persisted on Flutter Web

Extension of https://stackoverflow.com/a/58158636

In the new library version, onAuthStateChanged getter is not available. Instead of that use authStateChanges().

User firebaseUser = await FirebaseAuth.instance.currentUser;
  if (firebaseUser == null) {
    firebaseUser = await FirebaseAuth.instance.authStateChanges().first;
  }

https://pub.dev/documentation/firebase_auth/latest/firebase_auth/FirebaseAuth/authStateChanges.html


Firebase Dart Package

Import this pub and check the OS wherever auth is used

import 'package:firebase/firebase.dart' as firebase;
import 'package:firebase_auth/firebase_auth.dart';

if(Platform.isIOS || Platform.isAndroid) {
    FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password).then(() {
        //do something
    });
} else {
    firebase.auth().createUserWithEmailAndPassword(email, password).then(() {
        //do something
    });
}

Login happens automatically and it is handled by Firebase, however in async way. More details can be found in the official documentation:

https://firebase.google.com/docs/auth/web/auth-state-persistence

The trick is very simple. You need to wait for the first state change.

  static Future<User> getFirebaseUser() async {
    await init();
    //return await auth().currentUser;
    return await auth().onAuthStateChanged.first;
  }

It returns null if there is no signed-in user: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#onauthstatechanged

My firebase version:

firebase: 5.0.4 #https://pub.dartlang.org/packages/firebase

I wrote this implementation which works on both mobile and web:

  static Future<FirebaseUser> getFirebaseUser() async {
    FirebaseUser firebaseUser = await FirebaseAuth.instance.currentUser();
    if (firebaseUser == null) {
      firebaseUser = await FirebaseAuth.instance.onAuthStateChanged.first;
    }
    return firebaseUser;
  }