【发布时间】:2020-09-22 16:32:00
【问题描述】:
我是 Flutter 的新手。 我有一个函数可以按类型保留距离最接近某个值的所有元素。 所以我想要一个元素列表,它们都有不同的类型,并且对于每种类型,距离值最接近我作为参数输入的值。
当我不使用类但现在我想使用我的类但它不起作用时它可以工作......
我的功能无需类就可以工作:
function getItemsValid(List items, int distance){
List<Map<String, dynamic>> _lastDistanceByItems = items
.cast<Map<String, dynamic>>()
.fold(<int, Map<String, dynamic>>{}, (Map<int, Map<String, dynamic>> map, item)
{
final int _type = item['type'];
if (distance <= item['distance']) map[_type] = {"type" : item['type']};
return map;
}).values.toList();
}
我在课堂上的功能不起作用:
function getItemsValid(List items, int distance){
List<Item> _lastDistanceByItems = items
.cast<Item>()
.fold(<int, Item>{}, (Map<int, Item> map, item)
{
final int _type = item.type;
if (distance <= item.distance) map[_type] = {"type" : item.type}; // This not works
return map;
}).values.toList();
}
我的班级项目:
class Item{
int type;
int distance;
Item({
this.type,
this.distance,
});
Map<String, dynamic> toJson() => {
'type': type.toString(),
'distance': distance.toString(),
};
@override
String toString() {
return '{ '
'${this.type}, '
'${this.distance}, '
'}';
}
}
【问题讨论】: