我有一个嵌套的Json产品,我想按嵌套在json结构中的产品价格对其进行排序。现在,当我尝试按价格排序时,出现错误,但我不明白该错误:
Class 'List<Product>' has no instance getter 'sizes'.
Receiver: Instance(length:5) of '_GrowableList'
Tried calling: sizes
如果我想对嵌套过滤器进行排序,我不应该调用尺寸吗?我无法使案例1或2正常工作。
我正在尝试像这样过滤我的:
void _sortProductsDropDown(_fabSort) {
var tempProducts;
setState(() {
switch (_fabSort) {
case 0:
tempProducts = [];
break;
case 1:
tempProducts =
filteredProducts.sizes.sort((a, b) => a.price.compareTo(b.price));
print('Attempt $tempProducts');
break;
case 2:
tempProducts = filteredProducts
.Sodium.sort;
print('Sodium sort + ${tempProducts.length}');
break;
case 3:
tempProducts =
filteredProducts.where((e) => e.caloriesContent == 0.0).toList();
print(‘no cal ${tempProducts}');
break;
}
});
}
我的json数据
"id": 49,
"name": “Celery Combo”,
"short_description": “Yummy no calories”,
"quantity": 26,
"sizes": [
{
"id": 47,
"size": 6,
"product_id": 49,
"price": 8.99
}
],
"image": "https://ges3334.amazonaws.com/product_images/
“sodium,”: 7.0
},
{
"id": 48,
"name": “Beef Burger“,
"short_description": “Mad Cow Calories”,
"quantity": 30,
"sizes": [
{
"id": 46,
"size": 6,
"product_id": 48,
"price": 8.99
}
],
"image": "https://ges3334.amazonaws.com/product_images/single_cRIoNU8.png",
“calorie”: 1200.0,
“sodium”: 26.0
}
]
}
最佳答案
列表没有尺寸属性,尺寸是每个产品的属性。这是此行生成的
filteredProducts.sizes.sort((a, b) => a.price.compareTo(b.price));
并明确报告:
Class 'List<Product>' has no instance getter 'sizes'.
Receiver: Instance(length:5) of '_GrowableList'
Tried calling: sizes
在您的评论中,您说要按价格对产品进行排序,通过查看
sizes
列表中的第一个项目可以找到产品的价格。这很容易实现(在这里我使用了辅助函数,但是也可以使用lambda):
int compareProductBySmallestSize(Product lhs, Product rhs) {
var lhsPrice = lhs.sizes[0].price;
var rhsPrice = rhs.sizes[0].price;
return lhsPrice.compareTo(rhsPrice);
}
void _sortProductsDropDown(_fabSort) {
// ...
products.sort(compareProductBySmallestSize);
// ...
}
请注意,如果允许使用
sizes
列表为空的产品,则必须在助手功能中进行一些小的修改。
关于sorting - 在Flutter中对嵌套列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61067646/