[英]Flutter: Mapping updated values to all documents in firestore
我正在尝试通过在“开始时间”字段中添加一个小时并更新每个文档来更新我收藏中的所有文档。 但是,按下按钮后,它只获取该行的值,然后所有时间都更新为该值。 我想获取所有不同的时间,更新它们,然后将它们设置回各自的文档。
我的方法:
attempt2(DocumentSnapshot<Object?> snapshot) async {
FirebaseFirestore.instance
.collection('products')
.get()
.then((querySnapshot) {
for (var doc in querySnapshot.docs) {
doc.reference.update({
'Start Time': (DocumentSnapshot documentSnapshot) {
Timestamp timestamp = documentSnapshot.get('Start Time');
late DateTime d = timestamp.toDate().add(Duration(hours: 1));
return d;
}(snapshot),
});
}
});
}
和我的onPressed:
onPressed: () {
attempt2(documentSnapshot);
},
我认为发生这种情况是因为它是 DocumentSnapshot 而不是 QuerySnapshot? 但我不确定如何重构它。 第一张图片是在我点击之前,第二张图片是在我按下第一行的按钮之后。
我将不胜感激任何帮助。
好吧,只是乱搞它,我偶然发现了自己的答案,希望这对其他人有帮助:
我将方法更改为 QuerySnapshot,并将 (snapshot) 从我的 for 循环更改为var
(doc)。
attempt2(QuerySnapshot<Object?> snapshot) async {
FirebaseFirestore.instance
.collection('products')
.get()
.then((querySnapshot) {
for (var doc in querySnapshot.docs) {
doc.reference.update({
'Start Time': (DocumentSnapshot documentSnapshot) {
Timestamp timestamp = documentSnapshot.get('Start Time');
late DateTime d = timestamp.toDate().add(Duration(hours: 1));
return d;
}(doc),
});
}
});
}
然后,在我的 stream 内部,但在我的表格行之外,我添加了一个按钮:
ElevatedButton(
onPressed: () async {
await attempt2(snapshot.data!);
},
现在它用自己的数据更新每个文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.