简体   繁体   中英

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: () {
                    attempt2(documentSnapshot);
                  },

I think this happens because it is a DocumentSnapshot and not a 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.

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:

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

Now it updates each document with its own data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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