#我一直在关注 twitter 克隆的 youtube 项目,将 _userFromFirebaseUser 放入 map() 时出现错误;#
##我在 13:29 收到错误,这是链接。https://www.youtube.com/watch?v=YI7avcWI3aQ&t=919s ##
##我在终端收到的错误是Launching lib\main.dart on sdk gphone x86 arm in debug mode... lib\main.dart:1 lib/services/auth/auth.dart:13:40: Error :参数类型'UserModel?函数(用户)”不能分配给参数类型“用户模型函数(用户?)”,因为“用户模型?” 可以为空,而 'UserModel' 不是。
- 'UserModel' 来自'package:twitterclone/models/users.dart' ('lib/models/users.dart')。
- '用户'来自'package:firebase_auth/firebase_auth.dart'('../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/firebase_auth-1.0.1/lib/firebase_auth.dart' )。返回 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);
}
}
}