error: The argument type 'UserModel? Function(User?)' can't be assigned to the parameter type 'UserModel Function(User?)'

I am getting the following error in flutter.

UserModel is a class

class UserModel {
  final String uid;
  UserModel({this.uid});
}

And the code where this error is coming up is

  Stream<UserModel> get user {
    return _auth.authStateChanges()
        .map(_userFromFirebaseUser);
  }

Complete code:

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

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

  Stream<UserModel> get user {
    return _auth.authStateChanges()
        .map(_userFromFirebaseUser);
  }


  Future signInAnon() async {
    try {
      UserCredential result = await _auth.signInAnonymously();
      User user = result.user!;
      return _userFromFirebaseUser(user);

    } catch (e) {
      print(e.toString());
      return null;
    }

  }
  Future signInWithEmailAndPassword( String email, String password) async {
    try {
      UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      User user = result.user!;
      return _userFromFirebaseUser(user);
    } catch(e){
      print(e.toString());
      return null;
    }
  }

  Future signUpWithEmailAndPassword( String email, String password) async {
    try {
      UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      User user = result.user!;
      return _userFromFirebaseUser(user);
    } catch(e){
      print(e.toString());
      return null;
    }
  }

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

    }
  }



}

Solution 1:

This is happening because your _userFromFirebaseUser is defined something like this,

UserModel? _userFromFirebaseUser(User? user) {

So this means that you are saying, your _userFromFirebaseUser might return a UserModel or might return a null.

One way to fix this is to make your getter return Stream<UserModel?> instead of Stream<UserModel>.

Stream<UserModel?> get user {
  return _auth.authStateChanges()
    .map(_userFromFirebaseUser);
}

Now your getter might return a UserModel or it might return a null.