简体   繁体   中英

How to get sum of firestore document values using fold? Flutter

body: StreamBuilder<QuerySnapshot>(
      stream: record,
      builder:
          (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          ..........

          ..........
        final totalIncome =
            snapshot.data?.docs.fold<double>(0, (previousValue, element) {
          return previousValue + (element['incomeAmount'] ?? 0.0);
        }) as double;

     ...........
     ...........

This works if a field exists. If there is no field in firestore this gives an error field does not exist within the DocumentSnapshotPlatform

How can I make it work something like

element?['incomeAmount']

or if there is no field return 0?

You can make a function to get the totalAmount . It can be look like this

 int totalCost = 0;

  void getTotal() {
    FirebaseFirestore.instance.
        .collection('your_collection_name')
        .snapshots()
        .listen(event) {
      totalCost = (event.docs.fold<int>(
        0,(p, c) => prev + (Model.fromJson(c.data() as Map<String, dynamic>).amount),
      );
    });
  }

Then in the didChangeDependencies you can write this code,

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (mounted) {
      getTotal();
    }
  }

Finally, you can show the value of totalCost wherever you want.

 Text(totalCost.toString()),

You can see this GIF to check if it is correct or wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM