嗨,flutter 和 firebase 新手,我尝试做的是简单的注册新用户,然后使用自定义 id 将其信息添加到云 Firestore 并添加子集合名称“通知” 这里是代码示例..
final _auth = FirebaseAuth.instance;
final _ref = FirebaseFirestore.instance;
final userCollections = FirebaseFirestore.instance.collection("users");
Future<void> SignupToColud(
{@required String name = "",
@required String email = "",
@required String pass = ""}) async {
try {
await _auth
.createUserWithEmailAndPassword(email: email, password: pass)
.then((value) {
String userId = value.user.uid;
if (userId != null) {
userCollections.doc(userId).set({'name': name, 'email': email});
userCollections
.doc(userId)
.collection("notifications")
.add({'txt': 'welcome you registered as new user succefully'});
} else {
throw Error();
}
});
// first sign up to cloud if success
//then add to users collections
} catch (e) {
print(e.toString());
}
}
i got this error !!
lib/Sign_up.dart:24:36: Error: Property 'uid' cannot be accessed on 'User?' because it is potentially null.
- 'User' is from 'package:firebase_auth/firebase_auth.dart' ('/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_auth-1.2.0/lib/firebase_auth.dart').
Try accessing using ?. instead.
String userId = value.user.uid;
^^^
this is pubspec.yaml file information
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
lib/Sign_up.dart:24:36: Error: Property 'uid' cannot be accessed on 'User?' because it is potentially null.
- 'User' is from 'package:firebase_auth/firebase_auth.dart' ('/C:/src/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_auth-1.2.0/lib/firebase_auth.dart').
Try accessing using ?. instead.
String userId = value.user.uid;
^^^
我真的不知道这个问题以及如何解决它:(
答案 0 :(得分:0)
错误来自这一行:
String userId = value.user.uid;
正如错误所说的 value.user
是一个 User?
,这意味着它可以是一个 User
对象或它可以是 null
。您的代码需要处理这个可以为 null 的事实,因为只有您可以决定在这种情况下做什么。
我想你想要什么:
_auth
.createUserWithEmailAndPassword(email: email, password: pass)
.then((value) {
if (value.user != null) {
String userId = value.user!.uid;
userCollections.doc(userId).set({'name': name, 'email': email});
所以这会检查 value.user
是否为空(而不是检查 userId
。如果 value.user
不为空,则 uid
保证有一个值,所以我们可以在写操作中使用它。