I have been able to group data from a field. However I want get the sum of element in a field for each group. But I can’t figure that out. Can anyone help me? Or is there a better approach to go this?
I need help, please. Thank you.
StreamBuilder(
stream: FirebaseFirestore.instance
.collectionGroup(widget.userRequestCollection)
.where("Pay", isEqualTo: "Paid")
.snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text(widget.errorString);
}
if (snapshot.hasData) {
return GroupedListView(
elements: snapshot.data!.docs,
groupBy: (element) => element['DepartureDate'],
groupSeparatorBuilder: (String groupByValue) =>
Text(groupByValue),
itemBuilder: (context, dynamic element) {
double amount = element["AmountPaid"];
/*I want to get the sum of all the amount from each
group but the '+=' is giving me error */
double sum += amount;
return Text("$sum");
},
order: GroupedListOrder.ASC,
);
}
return const Center(
child: Text("No data"),
);
},
)
2
Answers
If you want to use the (pretty new) sum operator for this, I have an example of how to use that in Flutter here. From that:
My data model is different from yours, but you should be able to similarly
aggregate(sum('AmountPaid'))
on the query, and then get the value withsnapshot.getSum("AmountPaid")
.how about this?