我想根据销售折扣对产品列表进行排序。我知道如何计算 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());
}
尝试一下:
products.sort((a, b) {
double discountA = countDiscount(a);
double discountB = countDiscount(b);
return discountB.compareTo(discountA);
});