Flutter Firebase get sum of elements from data

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) {
                var col = FirebaseFirestore.instance
                .collectionGroup(widget.userRequestCollection);
            final countVal = col.count().get();
            final aggregates = col
                .where("Pay", isEqualTo: "Paid")
                .where("DepartureTimestamp",
                    isGreaterThanOrEqualTo: Timestamp.fromDate(
                        DateTime(element["DepartureDate"])))
                .where("DepartureTimestamp",
                    isGreaterThanOrEqualTo: Timestamp.fromDate(
                        DateTime(element["DepartureDate"])
                            .add(const Duration(days: 1))))
                .aggregate(
                  sum(element["AmountPaid"]),
                  average(element["AmountPaid#"]),
                  count(),
                )
                .get();
              },
              order: GroupedListOrder.ASC,
            );
            
          }
          return const Center(
            child: Text("No data"),
          );
        },
      )

code

Leave a Comment