【问题标题】:Flutter Firebase CloudFirestore shopping App need to get sum of all products from cloudfirestoreFlutter Firebase Cloud Firestore 购物 App 需要从 Cloud Firestore 获取所有产品的总和
【发布时间】:2020-01-30 18:08:58
【问题描述】:

我正在使用 Flutter Firebase cloudfirestore 应用程序创建购物应用程序。所以,我在实现购物车页面时遇到了问题。产品的所有详细信息都来自 firestore 集合('cart'),现在我想从 'cart' 集合中的所有文档中添加所有这些产品的价格,即简而言之想添加所有的价格字段存在于名为“购物车”的集合中的文档,并通过文本小部件显示。我怎么能做到。

【问题讨论】:

  • 写入数据时最好添加一个“总计”字段

标签: android firebase flutter google-cloud-firestore


【解决方案1】:

Firestore 没有任何聚合操作,例如 sum、avg、count 等。您需要做的是查询购物车集合中的所有文档,迭代这些文档,然后自己计算总和。或者,随着购物车内容的变化,您可以在另一个文档中维护一个运行总和。

【讨论】:

  • 您能分享任何代码 sn-p 或其他对文档中的字段求和的代码吗?谢谢您的回答
【解决方案2】:

在向 Firebase 提交数据之前。创建一个“总计”字段,以便接收项目的总数。

下面,widget.itemname 和 widget.rates 是保存数据的值。

您可以在 initState 中调用 getdata() 和 getTotal() 函数...

List yourItemList = [];
int getTotals = 0;    

   void getdata() {
    for (int i = 0; i < widget.itemName.length; i++)
      yourItemList.add({
        "name": widget.itemName.toList()[i],
        "quantity": widget.quantity.toList()[i],
        "price": widget.rate.toList()[i],
        "total": widget.quantity.toList()[i] * widget.rate.toList()[i],
      });
  }

  void getTotal() {
    for (int i = 0; i < yourItemList.length; i++)
      getTotals += yourItemList[i]['total'];
  }


Flatbutton(child: Text("submit"),
onPressed:(){
 _fireStore.collection('OrderDetails').add({
                'Customer': userName,
                "address": controller.text,
                "mobile": mobileNumber,
                "Grand Total": getTotals,            #<--here the total goes...
                "Time": DateTime.now(),
                "geopoints": geopoint == null
                    ? "nolocation"
                    : GeoPoint(geopoint.latitude, geopoint.longitude),
                "Item": FieldValue.arrayUnion(yourItemList),
              });}

【讨论】:

    猜你喜欢
    • 2018-09-25
    • 2022-01-16
    • 2021-05-27
    • 2019-07-11
    • 2018-04-30
    • 2020-11-08
    • 2022-06-24
    • 1970-01-01
    • 2021-05-09
    相关资源
    最近更新 更多