I have a scheduling app and one of my properties is DateTime. I want to be able to "push back" or "pull forwards" all timestamps, in hours/minutes, through user input. My problem is when trying to use my PushPull method, it requires an instance of DocumentSnapshot, which I don't know how to instantiate.
I have four text fields for pushing/pulling hours/minutes that look like this:
TextField( controller: pullHourController,
decoration: const InputDecoration(hintText: 'Hours'),
onChanged: (newValue) =>
pullHourController.setSelected(newValue),),
Then I parse the String to ints like:
late int pullHour = int.parse(pullHourController.text);
and my pushpull method I put on a button:
CollectionReference products =
FirebaseFirestore.instance.collection('products');
Future pushPull(DocumentSnapshot documentSnapshot) async {
Timestamp timestamp = await documentSnapshot.get('Start Time');
late DateTime d = timestamp.toDate();
late DateTime added = DateTime(d.year, d.month, d.day,
d.hour - pullHour pushHour, d.minute - pullMinute pushMinute);
await products.doc().set({'Start Time': added}).catchError((error) =>
{Get.snackbar("Failed to change time: $error", 'Please try again.')});
throw (e) => Get.snackbar('Error', (e).toString());
}
However, when I try to use this in my onPressed, I need a documentSnapshot as a positional argument, but it isn't locally available:
onPressed: () async {
pushPull();
},
I've tried getting rid of the brackets like pushPull
but nothing happens when its clicked.
CodePudding user response:
There is no atomic operation to update all documents in one go. Since your new value depends on the existing value, you will need to:
Read all documents from the collection.
Loop through them one by one in your application code.
Calculate the new value for each document, and write that back to the database.