Almog
Almog

Reputation: 2837

Issue when updating Firebase in Flutter App with current user

I just updated Google Firebase Auth in Flutter app because I was getting some wried SDK errors but now I'm getting

Error: 'currentUser' isn't a function or method and can't be invoked.
    var user = await _firebaseAuth.currentUser(); 

I looked at the migration guide and understand that currentUser() is now synchronous via the currentUser getter. but I'm not sure how I should change my code now to fix this.

My code

 class Auth implements BaseAuth {
  final auth.FirebaseAuth _firebaseAuth = auth.FirebaseAuth.instance;

  @override
  Future<String> signIn(String email, String password) async {
    var result = await _firebaseAuth.signInWithEmailAndPassword(
        email: email, password: password);
    var user = result.user;
    return user.uid;
  }

  @override
  Future<String> signUp(
      String email, String password, String name, String company) async {
    final userReference = FirebaseDatabase.instance.reference().child('users');
    var result = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
    var user = result.user;
    await userReference
        .child(user.uid)
        .set(User(user.uid, email, name, company).toJson());
    return user.uid;
  }

  @override
  Future<auth.User> getCurrentUser() async {
    var user = await _firebaseAuth.currentUser();
    return user;
  }

  @override
  Future<void> signOut() async {
    return _firebaseAuth.signOut();
  }

  @override
  Future<void> sendEmailVerification() async {
    var user = await _firebaseAuth.currentUser();
    await user.sendEmailVerification();
  }

  @override
  Future<void> resetPassword(String email) async =>
      await _firebaseAuth.sendPasswordResetEmail(email: email);

  @override
  Future<bool> isEmailVerified() async {
    var user = await _firebaseAuth.currentUser();
    return user.isEmailVerified;
  }
}

Upvotes: 2

Views: 1384

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598901

It looks like you're using the latest version of the FlutterFire libraries with outdated code.

In previous versions of the libraries, currentUser() was a method, that you had to await. In the latest versions of the library it's a property, and you no longer have to await its result.

So

var user = _firebaseAuth.currentUser;

Also see the documentation on using Firebase Authentication in your Flutter app, specifically the section on monitoring authentication state as it provides a way to listen for updates to the authentication state.

Upvotes: 8

Related Questions