[英]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.