我正在尝试仅更新文档中的一个字段 但如果我没有给它们一个值,另一个字段将设置为 null。
这是我的代码
Future updateUser({
String? uid,
String? displayName,
String? email,
String? phoneNumber,
String? photoURL,
String? creationTime,
}) async {
return await usersCollection.doc(uid).update({
"id": uid,
"displayName": displayName,
"email": email,
"phoneNumber": phoneNumber,
"photoURL": photoURL,
"type": 'Not Admin',
"isApproved": false,
"creationTime": creationTime,
});
}
我可以更新单个字段而不为每个要更新的字段创建方法吗?
因此,如果我想更新 displayName
,我只需将 displayName
传递给该方法,并保留其他字段不变。
请帮助我找到更好的方法
最佳答案
以下是实现您想要的功能的一种方法的示例:
Future updateUser({
String? uid,
String? displayName,
String? email,
String? phoneNumber,
String? photoURL,
String? creationTime,
}) async {
Map<String, dynamic> userData = {
"type": 'Not Admin',
"isApproved": false,
};
if (uid != null) {userData['uid'] = uid;}
if (displayName != null) {userData['displayName'] = displayName;}
if (email != null) {userData['email'] = email;}
if (phoneNumber != null) {userData['phoneNumber'] = phoneNumber;}
if (photoURL != null) {userData['photoURL'] = photoURL;}
if (creationTime != null) {userData['creationTime'] = creationTime;}
return await userCollection.doc(uid).update(userData);
}
如果 type
和 isApproved
从未改变,您可以从 userData 映射中删除它们。
关于flutter - 如何更新 firestore 文档中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69544381/