xenos92
xenos92

Reputation: 351

Flutter how to use a class in my functtion

I'm new with Flutter. I have a function that keeps all elements by type that have the distance closest to a certain value. So I want a list of elements that all have a different type and that for each type the distance value is the closest to my value entered as a parameter.

It works when I not use a class but now I want to use my class but it not works ...

My function who works without 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();
}

My function with my class NOT WORKS:

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();
}

My class Item:

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}, '
        '}';
  }
}

Upvotes: 2

Views: 139

Answers (1)

Abion47
Abion47

Reputation: 24781

You are trying to use cast to arbitrarily convert a collection of Map objects into Item objects. That's not how cast works - it takes a list of broadly-typed objects and converts it into a list of more narrowly-typed objects. For example, if you had a List<dynamic> where you knew every object inside was a string, you could do cast<String>() to convert it into List<String>. However, if there is an object that is not a string in the list, that will result in an error.

Instead, you want to use map to explicitly define the conversion between a Map object and an Item object. The first step is to define a fromJson constructor in your Item class:

class Item {
  ...
  
  Item.fromJson(Map<String, dynamic> map) : this(
    type: map['type'], 
    distance: map['distance'],
  );
}

Using this constructor, so the implementation of the map function is simple:

List<Item> _lastDistanceByItems = items
    .map((elem) => Item.fromJson(elem))

After that, the call to fold should work just fine.

Upvotes: 2

Related Questions