'用户模型? Function(User)' 不能分配给参数类型 'UserModel Function(User?)' 因为 'UserModel?'可以为空并且“UserModel”不是

时间:2021-03-24 12:22:48

标签: flutter dart uid dart-null-safety

#我一直在关注 twitter 克隆的 youtube 项目,但在将 _userFromFirebaseUser 放入 map() 时出现错误;#

##我在 13:29 出现错误,这是链接。 https://www.youtube.com/watch?v=YI7avcWI3aQ&t=919s ##

##我在终端收到的错误是在调试模式下在 sdk gphone x86 arm 上启动 lib\main.dart... lib\main.dart:1 lib/services/auth/auth.dart:13:40: 错误:参数类型“UserModel?无法将 Function(User)' 分配给参数类型 'UserModel Function(User?)',因为 'UserModel?'可以为空,而“UserModel”则不能。

  • “UserModel”来自“package:twitterclone/models/users.dart”(“lib/models/users.dart”)。
  • 'User' 来自 'package:firebase_auth/firebase_auth.dart' ('../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.0.1/lib/firebase_auth 。镖')。 返回 auth.authStateChanges().map(_userFromFirebaseUser);

代码和目录

-users.dart

class UserModel {
 final String id;
 UserModel({required this.id});
}

-auth.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:twitterclone/models/users.dart';

class AuthService {
 FirebaseAuth auth = FirebaseAuth.instance;

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

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

  Future<void> signUp(email, password) async {
    try {
      User user = (await auth.createUserWithEmailAndPassword(
          email: email, password: password)) as User;
      _userFromFirebaseUser(user);
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        print('No user found for that email.');
      } else if (e.code == 'wrong-password') {
        print('Wrong password provided for that user.');
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> signIn(email, password) async {
    try {
      User user = (await auth.signInWithEmailAndPassword(
          email: email, password: password)) as User;

      _userFromFirebaseUser(user);
    } on FirebaseAuthException catch (e) {
      print(e);
    } catch (e) {
      print(e);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

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

由于 UserModel 可以为空,因此将参数也更改为可以为空

UserModel? _userFromFirebaseUser(User? user) ...