Home > OS >  The getter 'uid' not defined
The getter 'uid' not defined

Time:04-04

i'm trying to create a food track app on android studio, it's my first time and i'm working with firebase_auth 3.3.12. my code in the aut.dart is:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:my_firstapp/models/user_model.dart';

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  AuthService();

  // create user object based on FirebaseUser.
  UserModel _userFromUser(User) {
    return user != null ? UserModel(uid: user.uid) : null;
  }

  // auth change user stream
  Stream<UserModel> get user {
    return _auth.authStateChanges()
        .map(_userFromUser);

  }

  Future<UserModel> getUser() async {
    User user = await _auth.currentUser();
    return _userFromUser(user);
  }

  // sign in with email and password
  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      User user = result.user;
      return _userFromUser(user);
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

  // sign up with email and password
  Future registerWithEmailAndPassword(String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      User user = result.user;
      // create a new user document in database
      return _userFromUser(user);
    } catch(e) {
      print(e.toString());
      return null;
    }
  }

  // sign out
  Future signOut() async {
    try {
      return await _auth.signOut();
    } catch(e){
      print(e.toString());
      return null;
    }
  }

}

However i'm getting 2 errors: -The getter 'uid' isn't defined for the type 'Stream'; -The expression "await _auth.currentUser()" doesn't evaluate to a function, so it can't be invoked.

How can i rewrite the code? thanks

CodePudding user response:

The _auth.currentUser is not a function (it used to be, but changed about a year ago), but rather a property. It also isn't asynchronous, so you don't need await nor to return a Future.

So:

UserModel getUser() {
  User user = _auth.currentUser;
  return _userFromUser(user);
}

CodePudding user response:

In this code, your argument is capitalised ('User') but in the code block you write 'user'.

UserModel _userFromUser(User) {
    return user != null ? UserModel(uid: user.uid) : null;
  }

Furthermore, for _auth.currentUser(), you do not need to use await as it does not return a future.

  • Related