dart flutter 中根据 saleDiscount 进行排序

问题描述 投票:0回答:1

我想根据销售折扣对产品列表进行排序。我知道如何计算 salediscount 但不知道如何应用product.sort()

这是我计算销售折扣的方法


double countDiscount(ProductModel product)
{
   double discount=product.price-product.salePrice;

   return (discount*100)/product.price;


}

这是完整的代码

class Product {
  String title;
  double price;
  double salePrice;

  Product({required this.title, required this.price, required this.salePrice});

  
  @override
  String toString() {
    // TODO: implement toString
    return title.toString();
  }
}

List<Product> products = [
  Product(title: 'A', price: 300, salePrice: 150), //50%
  Product(title: 'B', price: 200, salePrice: 160), //20%
  Product(title: 'C', price: 500, salePrice: 500), //0%
  Product(title: 'D', price: 100, salePrice: 70), //30%
];

void main() {
  runApp(const MyApp());
  products.sort((a, b) {
    
    //code for comparision based on salePercentage O/P should be ; A D B C

    
  });
  print(products.toString());
}

flutter
1个回答
0
投票

尝试一下:

   products.sort((a, b) {
    double discountA = countDiscount(a);
    double discountB = countDiscount(b);
    return discountB.compareTo(discountA);
  });
© www.soinside.com 2019 - 2024. All rights reserved.