错误:参数类型“UserModel?函数(用户?)”不能分配给参数类型“用户模型函数(用户?)”

时间:2021-06-02 15:17:32

标签: flutter dart

我在颤振中遇到以下错误。

UserModel 是一个类

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

出现这个错误的代码是

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

完整代码:

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;

    }
  }



}

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为您的 _userFromFirebaseUser 是这样定义的,

UserModel? _userFromFirebaseUser(User? user) {

所以这意味着您的意思是,您的 _userFromFirebaseUser 可能会返回 UserModel 或可能会返回 null

解决此问题的一种方法是让您的 getter 返回 Stream<UserModel?> 而不是 Stream<UserModel>

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

现在您的 getter 可能会返回一个 UserModel,也可能会返回一个 null