'Update field in all documents by looping in Cloud Firestore collection in Flutter
I'm trying to loop through all documents in a collection and update one field in all of them.
Getting the field, and adding 1 hour:
DateTime parsedDateTime(DocumentSnapshot documentSnapshot) {
Timestamp timestamp = documentSnapshot.get('Start Time');
late DateTime d = timestamp.toDate().add(Duration(hours: 1));
return d;
}
My (attempt at a) loop:
Future<dynamic> pushedPulledTime(DocumentSnapshot<Object?> snapshot) async {
FirebaseFirestore.instance
.collection('products')
.get()
.then((querySnapshot) {
for (var doc in querySnapshot.docs) {
doc.reference.update({
'Start Time': parsedDateTime(snapshot),
});
}
});
}
And my button:
return Container(child: FutureBuilder<DocumentSnapshot>(
builder: (BuildContext context, snapshot) {
return ElevatedButton(
onPressed: () async {
await pushedPulledTime(snapshot.data!);
The error I get on pressed:
E/flutter (25251): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
I should add that I placed one document in the 'products' collection, with a timestamp in the 'Start Time' field, so I know it's not getting an empty value from firestore.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
