LoginSignup
58
31

More than 1 year has passed since last update.

[Dart/Flutter] MapからListへ、ListからMapへ変換

Last updated at Posted at 2020-02-28

適当なModelクラスを使用する

class Person {
  Person(this.name, this.age);

  String name;
  int age;
}

MapからListへの変換

適当なMapを用意これをList\に変換

final persons = {'Takahashi': 23, 'Hamasaki': 27, 'Kawasaki': 25};

1. forEachを使う

final list = [];
persons.forEach((k, v) => list.add(Person(k, v)));

2. Iterable forEach()を使う

final list = [];
persons.entries.forEach((e) => list.add(Person(e.key, e.value)));

3. Iterable map()を使う

final list = persons.entries.map((e) => Person(e.key, e.value)).toList();

ListからMapへの変換

適当なList<Person>を用意これをMapに変換

final persons = <Person>[]
..add(Person('Takahashi', 23))
..add(Person('Hamasaki', 27))
..add(Person('Kawasaki', 25));

1. Map.fromIterables()を使用する

final map = Map.fromIterables(persons.map((e) => e.name).toList(),persons.map((e) => e.age).toList());

2. Iterable forEach()を使用する

final map = {};
persons.forEach((person) => map[person.name] = person.age);

まとめ

MapからListへの変換なら、Iterable map()を使うと一行で変換できる。
ListからMapへの変換なら、Map.fromIterables()を使うと一行で変換できる。

58
31
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
31