unice
unice

Reputation: 2842

How to convert list to map in dart?

I'm new to dart. I'm trying to covert my Holiday class to Map to be used in my calendar. I tried using Map.fromIterable but it only convert it to <String, dynamic>?

class Occasion {
  final List<Holiday> holidays;


  Map<DateTime, List> toMap() {
    var map = Map.fromIterable(holidays,
        key: (e) => DateFormat('y-M-d').format(DateTime.parse(e.date)),
        value: (e) => e.name);
    print(map);
  }
}

class Holiday {
  final String date;
  final String name;

  Holiday({
    this.date,
    this.name,
  });

  factory Holiday.fromJson(Map<String, dynamic> parsedJson) {
    return Holiday(date: parsedJson['date'], name: parsedJson['name']);
  }
}

Upvotes: 0

Views: 467

Answers (1)

Saskia
Saskia

Reputation: 1056

There are two things: First: The type parameters of your returned map aren't right for the values you produce in fromIterable. You say it should be List, but in value: ... you are only producing a single String.

Secondly, as I said in my comment you need to help out the dart compiler here a little bit. The compiler isn't very smart. It doesn't see that you are only producing Strings in value. You need to tell him that.

To be fair. This might not be the problem of the compiler, but an overuse of the dynamic type in the collections library.

  Map<String, String> toMap() {
    var map = Map<String, String>.fromIterable(holidays,
        key: (e) => e.date,
        value: (e) => e.name );
    return map;
  }

Just remember: be precise with your types. If you run into type errors start putting additional type information everywhere you can. If you feel it's to cluttered after that, try removing them one spot at a time and see where it leads you.

Upvotes: 1

Related Questions