如何在Flutter中计算List中的一些数据。

huangapple go评论72阅读模式
英文:

How to count some data in List<Model> flutter

问题

我正在制作一个销售点应用程序,其中将显示要购买的商品列表,包括商品数量和价格。但我在计算总金额方面遇到了问题。

这是向 List 添加数据的代码部分:

final List<Product> listProduct;
widget.listProduct.add(data);

这是我的模型:

Product productFromJson(String str) => Product.fromJson(json.decode(str));

String productToJson(Product data) => json.encode(data.toJson());

class Product {
  final int id;
  final int categoryId;
  final String productName;
  final int productQuantity;
  final int productCost;
  final int productPrice;
  final String image;
  int quantity = 1;
  int total = 0;
  final DateTime createdAt;
  final DateTime updatedAt;

  Product({
    required this.id,
    required this.categoryId,
    required this.productName,
    required this.productQuantity,
    required this.productCost,
    required this.productPrice,
    required this.image,
    required this.createdAt,
    required this.updatedAt,
  });

  factory Product.fromJson(Map<String, dynamic> json) => Product(
        id: json["id"],
        categoryId: json["category_id"],
        productName: json["product_name"],
        productQuantity: json["product_quantity"],
        productCost: json["product_cost"],
        productPrice: json["product_price"],
        image: json['image'],
        createdAt: DateTime.parse(json["created_at"]),
        updatedAt: DateTime.parse(json["updated_at"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "category_id": categoryId,
        "product_name": productName,
        "product_quantity": productQuantity,
        "product_cost": productCost,
        "product_price": productPrice,
        "created_at": createdAt.toIso8601String(),
        "updated_at": updatedAt.toIso8601String(),
      };
}

我使用 DataTable 来显示列表数据:

DataTable(
   columns: const <DataColumn>[
      DataColumn(label: Text('No', style: TextStyle(fontStyle: FontStyle.italic))),
      DataColumn(label: Text('Product Name', style: TextStyle(fontStyle: FontStyle.italic))),
      DataColumn(label: Text('Price', style: TextStyle(fontStyle: FontStyle.italic))),
      DataColumn(label: Text('Amount', style: TextStyle(fontStyle: FontStyle.italic))),
      DataColumn(label: Text('Total', style: TextStyle(fontStyle: FontStyle.italic))),
      DataColumn(label: Text('Delete', style: TextStyle(fontStyle: FontStyle.italic))),
],
   rows: List.generate(widget.listProduct.length, (index) {
         Product dataProduct = widget.listProduct[index];
         int total = dataProduct.quantity * dataProduct.productPrice;
         String totalHarga = total.toString();
         return DataRow(
            cells: <DataCell>[
                    DataCell(Text('${index + 1}.')),
                    DataCell(Text(dataProduct.productName)),
                    DataCell(Text(dataProduct.productPrice.toString())),
                    DataCell(Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        IconButton(
                            onPressed: () {
                              setState(() {
                                if (dataProduct.quantity >= 2) {
                                  dataProduct.quantity--;
                                  total = dataProduct.quantity * dataProduct.productPrice;
                                } else {
                                  return;
                                }
                              });
                            },
                            icon: Icon(Icons.remove)),
                        Text(dataProduct.quantity.toString()),
                        IconButton(
                            onPressed: () {
                              setState(() {
                                dataProduct.quantity++;
                                total = dataProduct.quantity * dataProduct.productPrice;
                                print(total);
                              });
                            },
                            icon: Icon(Icons.add)),
                      ],
                    )),
                    DataCell(Text(totalHarga)),
                    DataCell(
                      Icon(Icons.delete),
                      onTap: () {
                        widget.listProduct.remove(dataProduct);
                        getProductData();
                      },
                    )
           ],
         );
       }
     ),
 )

你的移动屏幕截图如下所示:
如何在Flutter中计算List<Model>中的一些数据。

英文:

I'm making a point of sales application where there will be a list of items to be purchased along with the number of items and prices. but I'm having problems in making the total calculation.

this is my code to add data to List<Product>

final List&lt;Product&gt; listProduct;
widget.listProduct.add(data);

this is my model

Product productFromJson(String str) =&gt; Product.fromJson(json.decode(str));

String productToJson(Product data) =&gt; json.encode(data.toJson());

class Product {
  final int id;
  final int categoryId;
  final String productName;
  final int productQuantity;
  final int productCost;
  final int productPrice;
  final String image;
  int quantity = 1;
  int total = 0;
  final DateTime createdAt;
  final DateTime updatedAt;

  Product({
    required this.id,
    required this.categoryId,
    required this.productName,
    required this.productQuantity,
    required this.productCost,
    required this.productPrice,
    required this.image,
    required this.createdAt,
    required this.updatedAt,
  });

  factory Product.fromJson(Map&lt;String, dynamic&gt; json) =&gt; Product(
        id: json[&quot;id&quot;],
        categoryId: json[&quot;category_id&quot;],
        productName: json[&quot;product_name&quot;],
        productQuantity: json[&quot;product_quantity&quot;],
        productCost: json[&quot;product_cost&quot;],
        productPrice: json[&quot;product_price&quot;],
        image: json[&#39;image&#39;],
        createdAt: DateTime.parse(json[&quot;created_at&quot;]),
        updatedAt: DateTime.parse(json[&quot;updated_at&quot;]),
      );

  Map&lt;String, dynamic&gt; toJson() =&gt; {
        &quot;id&quot;: id,
        &quot;category_id&quot;: categoryId,
        &quot;product_name&quot;: productName,
        &quot;product_quantity&quot;: productQuantity,
        &quot;product_cost&quot;: productCost,
        &quot;product_price&quot;: productPrice,
        &quot;created_at&quot;: createdAt.toIso8601String(),
        &quot;updated_at&quot;: updatedAt.toIso8601String(),
      };
}

and i user DataTable to display list data

DataTable(
   columns: const &lt;DataColumn&gt;[
      DataColumn(label: Text(&#39;No&#39;,style: TextStyle(fontStyle: FontStyle.italic))),
      DataColumn(label: Text(&#39;Product Name&#39;,style: TextStyle(fontStyle: FontStyle.italic),),),
      DataColumn(label: Text(&#39;Price&#39;,style: TextStyle(fontStyle: FontStyle.italic),),),
      DataColumn(label: Text(&#39;Amount&#39;,style: TextStyle(fontStyle: FontStyle.italic),),),
      DataColumn(label: Text(&#39;Total&#39;,style: TextStyle(fontStyle: FontStyle.italic),),),
      DataColumn(label: Text(&#39;Delete&#39;,style: TextStyle(fontStyle: FontStyle.italic),),),
],
   rows: List.generate(widget.listProduct.length, (index) {
         Product dataProduct = widget.listProduct[index];
         int total = dataProduct.quantity * dataProduct.productPrice;
         String totalHarga = total.toString();
         return DataRow(
            cells: &lt;DataCell&gt;[
                    DataCell(Text(&#39;${index + 1}.&#39;)),
                    DataCell(Text(dataProduct.productName)),
                    DataCell(Text(dataProduct.productPrice.toString())),
                    DataCell(Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        IconButton(
                            onPressed: () {
                              setState(() {
                                // quantity--;
                                if (dataProduct.quantity &gt;= 2) {
                                  dataProduct.quantity--;
                                  total = dataProduct.quantity *
                                      dataProduct.productPrice;
                                } else {
                                  return;
                                }
                              });
                            },
                            icon: Icon(Icons.remove)),
                        Text(dataProduct.quantity.toString()),
                        IconButton(
                            onPressed: () {
                              setState(() {
                                dataProduct.quantity++;
                                total = dataProduct.quantity *
                                    dataProduct.productPrice;
                                print(total);
                              });
                            },
                            icon: Icon(Icons.add)),
                      ],
                    )),
                    DataCell(Text(totalHarga)),
                    DataCell(
                      Icon(Icons.delete),
                      onTap: () {
                        widget.listProduct.remove(dataProduct);
                        getProductData();
                      },
                    )
           ],
         );
       }
     ),
 ),

this is my mobile screen

答案1

得分: 0

使用这个方法:

double totalPrice(){
    double total = 0.0;
    for(Product product in productList){
      total += product.price * product.quantity;
    }
    return total;
}
英文:

use this method:

double totalPrice(){
    double total = 0.0;
    for(Product product in productList){
      total += product.price * product.quantity;
    }
    return total;
  }

huangapple
  • 本文由 发表于 2023年7月18日 15:04:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定