简体   繁体   English

Flutter:将更新值映射到 firestore 中的所有文档

[英]Flutter: Mapping updated values to all documents in firestore

I'm trying to update all of the documents in my collection by getting, adding an hour to the 'start time' field, and updating each document.我正在尝试通过在“开始时间”字段中添加一个小时并更新每个文档来更新我收藏中的所有文档。 However, upon pressing the button, it takes the value of that row only, then updates all times to that value.但是,按下按钮后,它只获取该行的值,然后所有时间都更新为该值。 I want to get all of the different times, update them and then set them back to their respective documents.我想获取所有不同的时间,更新它们,然后将它们设置回各自的文档。

My method:我的方法:

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),
        });
      }
    });
  }

and my onPressed:和我的onPressed:

onPressed: () {
                    attempt2(documentSnapshot);
                  },

I think this happens because it is a DocumentSnapshot and not a QuerySnapshot?我认为发生这种情况是因为它是 DocumentSnapshot 而不是 QuerySnapshot? But I'm not sure how to refactor it.但我不确定如何重构它。 First image is before I click, second is after I press the button in the first row.第一张图片是在我点击之前,第二张图片是在我按下第一行的按钮之后。

图片

图片

I would appreciate any help.我将不胜感激任何帮助。

Well, just messing around with it, I stumbled upon my own answer, hope this helps someone else:好吧,只是乱搞它,我偶然发现了自己的答案,希望这对其他人有帮助:

I changed the method to a QuerySnapshot, and changed the (snapshot) to the var (doc) from my for loop.我将方法更改为 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),
        });
      }
    });
  }

Then, inside of my stream, but outside of my table rows, I added a button:然后,在我的 stream 内部,但在我的表格行之外,我添加了一个按钮:

ElevatedButton(
                      onPressed: () async {
                        await attempt2(snapshot.data!);
                      },

Now it updates each document with its own data.现在它用自己的数据更新每个文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM