如何在Dart中基于saleDiscount对商品列表进行排序?
按折扣率对商品列表降序排序的Dart实现
完整解决方案代码
class Product { String title; double price; double salePrice; Product({required this.title, required this.price, required this.salePrice}); @override String 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%折扣 ]; // 修正参数类型为Product(匹配类定义) double countDiscount(Product product) { double discount = product.price - product.salePrice; return (discount * 100) / product.price; } void main() { // runApp(const MyApp()); // Flutter项目保留,纯Dart环境可注释 products.sort((a, b) { // 计算两个商品的折扣率 final discountA = countDiscount(a); final discountB = countDiscount(b); // 按折扣率降序排序:折扣高的商品排在前面 return discountB.compareTo(discountA); }); print(products.toString()); // 输出: [A, D, B, C] }
关键逻辑说明
- 修正折扣计算函数:将原函数的
ProductModel参数改为Product,匹配你的类定义,确保能正确计算每个商品的折扣率。 - 排序比较器实现:
List.sort()默认按升序排列,要实现降序(折扣从高到低),需要反转比较结果。- 使用
discountB.compareTo(discountA):当discountA大于discountB时,compareTo返回-1,此时a会被排在b前面,正好符合降序需求。 - 也可以用更直观的手动判断写法,效果完全一致:
if (discountA > discountB) return -1; if (discountA < discountB) return 1; return 0;
内容的提问来源于stack exchange,提问作者user22362195
相关产品推荐
相关产品推荐

