I am using Dart Flutter and Firebase Firestore.
I have a collection order
with auto-ID'd documents containing a name
and price
.
I want to set a double total
to a sum of every price in the collection 'order'.
I have set up a query snapshot, forEach
function, and docs.get()
method.
I have tried to set up as a map, and consulted chatGPT. The total isn't either updating or getting the price of each doc.
I have used an initState() { calculateTotal(); }
to call the function.
double total = 0;
Future<void> calculateTotal() async {
total = 0;
QuerySnapshot querySnapshot =
await FirebaseFirestore.instance.collection('order').get();
querySnapshot.docs.forEach((doc) {
total += doc.get('price');
});
}
@override
Widget build(BuildContext context) {
initState() {
calculateTotal();
}
QuerySnapshot<Map<String, dynamic>> querySnapshot =
await FirebaseFirestore.instance.collection('order').get();
querySnapshot.docs.forEach((doc) {
total += double.tryParse(doc['price']??"0")??0;
});
you can try this code snipped