Flutter: Mapping updated values to all documents in firestore

Viewed 104

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.

image

image

I would appreciate any help.

1 Answers

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.

Related