问题描述
#我一直在关注 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);
}
}
}
解决方法
在
UserModel? _userFromFirebaseUser(User user) {
// ignore: unnecessary_null_comparison
return user != null ? UserModel(id: user.uid) : null;
}
由于 UserModel
可以为空,因此将参数也更改为可以为空
UserModel? _userFromFirebaseUser(User? user) ...