Vishnu Darshan
Vishnu Darshan

Reputation: 388

Flutter Firebase CloudFirestore shopping App need to get sum of all products from cloudfirestore

I am creating a Shopping App with Flutter Firebase cloudfirestore Application. So, I am having a problem while implementing the cart Page. All the details of the products are coming from the firestore collection ('cart'), Now I want to add the price of all those products from all the documents inside the 'cart' collection i.e in short wanna add the price fields of all the documents present inside the collection named 'cart' and display via Text Widget. How could I achieve it.enter image description here

Upvotes: 0

Views: 1528

Answers (2)

Asbah Riyas
Asbah Riyas

Reputation: 986

Before submitting data to the firebase. Create a "Total" field, in order to receive a total of the items.

Below, the widget.itemname and widget.rates are the values that hold the data.

You can call the getdata() and getTotal() functions in initState...

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

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317467

Firestore doesn't have any aggregate operations, such as sum, avg, count, and so on. What you will have to do is query the cart collection for all of its documents, iterate those documents, and compute the sum yourself. Alternately, you can maintain a running sum in another document as the contents of the cart changes.

Upvotes: 1

Related Questions