英文:
Flutter : Sort list by quantity
问题
我想按数量对我的 List<Product> 列表进行排序。
我有一个包含在 List of color 里的 List of size,它们又包含在 List of product 里。
就像这样:
//数量为1
Product(
productId: '0',
purchasingPrice: 14.99,
productTitle: 'Empty',
productColors: [
ProductColors(
colorName: 'Red',
colorHex: 'ff000d',
productSize: [
ProductSizes(
size: 'L',
quantity: 0
),
ProductSizes(
size: 'M',
quantity: 1
),
ProductSizes(
size: 'S',
quantity: 0
)
]
)
]
),
//数量为5
Product(
productId: '1',
purchasingPrice: 39.99,
productTitle: 'Empty',
productColors: [
ProductColors(
colorName: 'Black',
colorHex: '000000',
productSize: [
ProductSizes(
size: 'XL',
quantity: 1
),
ProductSizes(
size: 'L',
quantity: 2
),
ProductSizes(
size: 'M',
quantity: 2
)
]
)
]
),
];
第一项有1个件,第二项有5个件。
我从未处理过嵌套列表 ![]()
英文:
i want sort my list List<Product> by quantity.
i have List of size inside List of color inside List of product
like this :
List<Product> _products = [
//quantity is 1
Product(
productId: '0',
purchasingPrice: 14.99,
productTitle: 'Empty',
productColors: [
ProductColors(
colorName: 'Red',
colorHex: 'ff000d',
productSize: [
ProductSizes(
size: 'L',
quantity: 0
),
ProductSizes(
size: 'M',
quantity: 1
),
ProductSizes(
size: 'S',
quantity: 0
)
]
)
]
),
//quantity is 5
Product(
productId: '1',
purchasingPrice: 39.99,
productTitle: 'Empty',
productColors: [
ProductColors(
colorName: 'Black',
colorHex: '000000',
productSize: [
ProductSizes(
size: 'XL',
quantity: 1
),
ProductSizes(
size: 'L',
quantity: 2
),
ProductSizes(
size: 'M',
quantity: 2
)
]
)
]
),
];
The first item has 1 piece and the Second has 5 pieces.
I have never dealt with nested list ![]()
答案1
得分: 1
请将类Product添加一个int类型的字段totalSize。
以下是如何对列表_products进行排序的示例代码:
int getTotalProductSize(Product product){
int totalSize = 0;
for(ProductColor productColor in product.productColors){
for(int i=0; i<productColor.productSize.length; i++){
totalSize += productColor.productSize[i].quantity;
}
}
return totalSize;
}
for(Product product in _products){
product.totalSize = getTotalProductSize(product);
}
_products.sort((a, b) => a.totalSize.compareTo(b.totalSize));
请注意,不建议使用如此复杂的模型。
英文:
Please add an int field totalSize to the class Product.
Here's how you can sort the list _products
int getTotalProductSize(Product product){
int totalSize = 0;
for(ProductColor productColor in product.productColors){
for(int i=0; i<productColor.productSize.length; i++){
totalSize += productColor.productSize[i].quantity;
}
}
return totalSize;
}
for(Product product in _products){
product.totalSize = getTotalProductSize(product);
}
_products.sort((a, b) => a.totalSize.compareTo(b.totalSize));
Please note that having such complex models is never recommended.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论