gpt4 book ai didi

Flutter 如何在我的函数中使用一个类

转载 作者:行者123 更新时间:2023-12-03 02:54:44 25 4
gpt4 key购买 nike

我是 Flutter 的新手。
我有一个函数可以按类型保留距离最接近某个值的所有元素。
所以我想要一个元素列表,它们都有不同的类型,并且对于每种类型,距离值最接近我作为参数输入的值。
当我不使用类(class)但现在我想使用我的类(class)但它不起作用时它可以工作......
我的无课工作职能:

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)货号:
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}, '
'}';
}
}

最佳答案

您正在尝试使用 cast任意转换 Map 的集合对象放入 Item对象。不是这样 cast工作 - 它需要一个广泛类型的对象列表并将其转换为一个更窄类型的对象列表。例如,如果您有一个 List<dynamic>如果你知道里面的每个对象都是一个字符串,你可以这样做 cast<String>()将其转换为 List<String> .但是,如果列表中有一个不是字符串的对象,则会导致错误。
相反,您想使用 map明确定义 Map 之间的转换对象和 Item目的。第一步是定义一个 fromJson Item 中的构造函数类(class):

class Item {
...

Item.fromJson(Map<String, dynamic> map) : this(
type: map['type'],
distance: map['distance'],
);
}
使用这个构造函数,所以执行 map功能很简单:
List<Item> _lastDistanceByItems = items
.map((elem) => Item.fromJson(elem))
之后,调用 fold应该可以正常工作。

关于Flutter 如何在我的函数中使用一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64013983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com