skip to Main Content

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


  1. 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:

    final startAt = Timestamp.fromDate(DateTime(2024, 01, 03));
    final endBefore = Timestamp.fromDate(DateTime(2024, 01, 04));
    final aggregates = await col
      .where('timestamp', isGreaterThanOrEqualTo: startAt)
      .where('timestamp', isLessThan: endBefore)
      .aggregate(
        sum('latency'),
        average('latency'),
        count(),
      ).get();
    print('''
      Logs on Jan 3:
        count=${aggregates.count}
        sum of latency=${aggregates.getSum("latency")}, 
        average latency=${aggregates.getAverage("latency")}
    ''');
    

    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 with snapshot.getSum("AmountPaid").

    Login or Signup to reply.
  2. how about this?

    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) {
                 // --- new code
                 double sum = element
                    .map((e) => e.data()['AmountPaid'])
                    .reduce((value, element) => value + element);;
                 // ---
                 return Text("$sum");
              },
              order: GroupedListOrder.ASC,
            );
            
          }
          return const Center(
            child: Text("No data"),
          );
        },
      )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search