简体   繁体   English

如何获取 Flutter firestore 中的值的总数?

[英]How To get The Total of values in Flutter firestore?

I have a Firestore Collection 'Cart' contains a List of Products and every Product has a price so I want to get all of them and calculate the sum of prices: FireStore Collection我有一个 Firestore Collection 'Cart' 包含一个产品列表,每个产品都有一个价格,所以我想获取所有这些产品并计算价格总和: FireStore Collection

I tried a some of code and this one is working but how I can show the sum on the Screen我尝试了一些代码,这个代码正在工作,但是我如何在屏幕上显示总和

  Future getTotal() async {
int sum = 0;
FirebaseFirestore.instance.collection('Users/$userid/Cart').get().then(
  (querySnapshot) {
    querySnapshot.docs.forEach((result) {
      for (var i = 1; i < result.data()['price'].toString().length; i++) {
        sum = sum + result.data()['price'];
      }
    });
    print('total : $sum');
  },
);
}

Capture from Cart Screen从购物车屏幕捕获

Update: I Tried this is Working but when I delete a product from the cart the value didn't change Except when I Close The screen and then come back again,更新:我试过这是有效的,但是当我从购物车中删除产品时,值没有改变除非我关闭屏幕然后再回来,

  double sum = 0;
   double total = 0;
  final String userid = FirebaseAuth.instance.currentUser.uid;

 @override
 void initState() {
   FirebaseFirestore.instance.collection('Users/$userid/Cart').get().then(
    (querySnapshot) {
      querySnapshot.docs.forEach((result) {
      sum = sum + result.data()['price'];
      });
    setState(() {
      total = sum;
      });
    },
   );
  super.initState();
 }

any help will be appreciated.任何帮助将不胜感激。

this Works for me:这对我有用:

 final cartitems = snapshot.data;
            final List<CartModel> products = cartitems;
            double getPrice() {
              double price = 0;
              cartitems.forEach((x) {
                price += x.price * x.numofitem;
              });
              return price;
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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