the*_*der 4 dart firebase flutter google-cloud-firestore
我想更新一个文档字段,我已经尝试了以下代码,但它没有更新。
任何人都可以给我一个解决方案吗?
我的代码:
var snapshots = _firestore
.collection('profile')
.document(currentUserID)
.collection('posts')
.snapshots();
await snapshots.forEach((snapshot) async {
List<DocumentSnapshot> documents = snapshot.documents;
for (var document in documents) {
await document.data.update(
'writer',
(name) {
name = this.name;
return name;
},
);
print(document.data['writer']);
//it prints the updated data here but when i look to firebase database
//nothing updates !
}
});
Run Code Online (Sandbox Code Playgroud)
Fra*_*len 12
对于这种情况,我总是建议遵循文档中的确切类型,以查看可用的选项。例如,DocumentSnapshot对象的data属性是 a Map<String, dynamic>。当您调用update()它时,您只是更新文档的内存表示,而不是实际更新数据库中的数据。
要更新数据库中的文档,您需要调用DocumentReference.updateData方法。并且要从DocumentSnapshota 到 a DocumentReference,您需要调用该DocumentSnapshot.reference属性。
所以像:
document.reference.updateData(<String, dynamic>{
name: this.name
});
Run Code Online (Sandbox Code Playgroud)
与此无关,您的代码看起来有点不习惯。我建议使用getDocuments而不是snapshots(),因为后者可能会导致无限循环。
var snapshots = _firestore
.collection('profile')
.document(currentUserID)
.collection('posts')
.getDocuments();
await snapshots.forEach((document) async {
document.reference.updateData(<String, dynamic>{
name: this.name
});
})
Run Code Online (Sandbox Code Playgroud)
这里的区别在于getDocuments()读取数据一次,然后返回它,同时snapshots()将开始观察文档,并在发生更改时(包括更新名称时)将它们传递给我们。
| 归档时间: |
|
| 查看次数: |
9475 次 |
| 最近记录: |