【问题标题】:Flutter firestore sum all the field values according to daily recordFlutter firestore根据每日记录对所有字段值求和
【发布时间】:2022-01-30 02:25:41
【问题描述】:

我是 Flutter 和 Firestore 开发的新手。我有一个 SalesRecord 集合和一个名为 SellingPrice 的字段名称。如何根据日常记录将 SellingPrice 的所有值求和并打印出所有这些总和值。

更新代码:-

FutureBuilder(
        future: FirebaseFirestore.instance.collection('SalesRecord').get(),
        builder: (BuildContext context,
            AsyncSnapshot<QuerySnapshot> querySnapshot) {
          if (querySnapshot.hasError) {
            return Text("Something went wrong");
          }

          // if (snapshot.hasData && !snapshot.data!.exists) {
          //   return Text("Document does not exist");
          // }

          if (querySnapshot.connectionState == ConnectionState.done) {
            querySnapshot.data!.docs.forEach((doc) {
              sumTotal = sumTotal +
                  doc["SellingPrice"]; // make sure you create the variable sumTotal somewhere
            });
            return Text("Sum of all sells: ${sumTotal}");
          }

          return Text("loading");
        },
      ),

【问题讨论】:

  • 所以,如果我猜对了,您的 SalesRecord 集合中包含的每个 document 都有一个名为 SellingPrice 的字段,您希望获取所有 SellingPrice 字段的值的总和
  • @TimothyOfie 是的,假设我今天有 20 笔销售,售价不同,我想总结今天所有的售价并每天更新售价的总和。
  • @BJW 下面的答案可以正常工作,尽管这取决于您想要什么,为了获得干净的体验,您可以选择使用 Firebase Cloud Functions 自动将所有 SellingPrice 值汇总到一个字段中在一天结束时,但为了获得快速简便的解决方案,您可以应用下面按日期排序的答案

标签: firebase flutter dart


【解决方案1】:

查看https://api.flutter.dev/flutter/widgets/FutureBuilder-class.htmlhttps://firebase.flutter.dev/docs/firestore/usage/ 了解详细信息。下面的例子应该会给你带来你所需要的。

对于您的情况,您应该在 FutureBuilder 中使用 builder 尝试:

FutureBuilder(
    future: FirebaseFirestore.instance
        .collection('SalesRecord')
        .get(),
    builder:
      (BuildContext context, AsyncSnapshot<QuerySnapshot> querySnapshot) {

    if (snapshot.hasError) {
      return Text("Something went wrong");
    }

    if (snapshot.hasData && !snapshot.data!.exists) {
      return Text("Document does not exist");
    }

    if (snapshot.connectionState == ConnectionState.done) {
      querySnapshot.data!.docs.forEach((doc) {
        sumTotal = sumTotal + doc["SellingPrice"]; // make sure you create the variable sumTotal somewhere
      });
      return Text("Sum of all sells: ${sumTotal}")
    }

    return Text("loading");
  },
),

【讨论】:

  • 感谢您的回复,我会试试看。
  • 我收到此错误 NoSuchMethodError: '+' Dynamic call of null。接收者:空参数:[3500]
  • 您是否在文件中的其他位置初始化了 sumTotal?
  • 是的,但出现此错误
  • 请添加完整代码并添加打印语句以查看 doc["SellingPrice"] 是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2020-01-14
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
相关资源
最近更新 更多