Flutter技术问询:如何按总数量排序嵌套结构的List<Product>
按嵌套列表的总数量排序List
要实现按每个Product的总库存数量排序,核心是先计算每个Product的总数量,再基于这个数值对列表排序。
步骤1:计算单个Product的总数量
可以写一个辅助函数来累加嵌套列表里的quantity,用Dart的fold方法会更简洁:
int calculateTotalQuantity(Product product) { // 先累加每个颜色下的所有尺码数量,再累加所有颜色的总和 return product.productColors.fold(0, (totalColor, color) { return totalColor + color.productSize.fold(0, (totalSize, size) => totalSize + size.quantity); }); }
如果习惯用循环写法,也可以这样写:
int calculateTotalQuantity(Product product) { int total = 0; for (final color in product.productColors) { for (final size in color.productSize) { total += size.quantity; } } return total; }
步骤2:对List排序
调用列表的sort方法,传入比较器,用上面的函数计算两个Product的总数量后对比:
// 升序排序(总数量从小到大) _products.sort((a, b) { final totalA = calculateTotalQuantity(a); final totalB = calculateTotalQuantity(b); return totalA.compareTo(totalB); }); // 如果需要降序排序(总数量从大到小),只需调换对比顺序 _products.sort((a, b) { final totalA = calculateTotalQuantity(a); final totalB = calculateTotalQuantity(b); return totalB.compareTo(totalA); });
效果验证
用你给出的示例数据:
- 第一个Product总数量为1,第二个为5
- 升序排序后列表顺序不变;降序排序后第二个Product会排在第一位
注意事项
- 如果
productColors或productSize为空列表,fold方法会返回初始值0,不会报错 - 辅助函数可以单独提取,也可以直接把计算逻辑写在
sort的比较器里,但单独提取更利于代码维护和复用
内容的提问来源于stack exchange,提问作者x98lol
相关产品推荐
相关产品推荐

