【问题标题】:Flutter how to use a class in my functtionFlutter 如何在我的函数中使用一个类
【发布时间】: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}, '
        '}';
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您正在尝试使用castMap 对象的集合任意转换为Item 对象。 cast 不是这样工作的——它需要一个广泛类型的对象列表并将其转换为一个更窄类型的对象列表。例如,如果您有一个List&lt;dynamic&gt;,您知道其中的每个对象都是一个字符串,您可以使用cast&lt;String&gt;() 将其转换为List&lt;String&gt;。但是,如果列表中有一个不是字符串的对象,则会导致错误。

    相反,您想使用map 显式定义Map 对象和Item 对象之间的转换。第一步是在Item 类中定义一个fromJson 构造函数:

    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 的调用应该可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 2022-01-05
      • 2022-12-11
      • 2021-11-23
      • 2021-11-11
      • 2019-11-15
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多