首页 > 解决方案 > Flutter Firebase CloudFirestore 购物 App 需要从 cloudfirestore 获取所有产品的总和

问题描述

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

标签: androidfirebasefluttergoogle-cloud-firestore

解决方案


在向 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),
              });}

推荐阅读