Dart Map to List Tutorial – Coding Example

Dart Map to List

Dart/Flutter Convert Map to List Tutorial

In the tutorial, I introduce details how to convert Dart/Flutter Map to List with example coding.
– Using Dart Map forEach() method
– Using Iterable forEach() method
– Using Iterable map() method


Before starting, we create a data model class as below:


class Customer {
  String name;
  int age;

  Customer(this.name, this.age);

  @override
  String toString() {
    return '{ ${this.name}, ${this.age} }';
  }
}

Now we initialize a Dart Map data:

Map map = {'Jane': 21, 'Mary': 34, 'Peter': 40};

We will convert this Dart Map to List:
– an key of the Map’s entry is to be name property of a Customer object
– an value of the Map’s entry is to be age property of a Customer object

Using Map forEach() method

map.forEach((k, v) => list.add(Customer(k, v)));
print(list);

In the code above, we create a new Customer object from each key-value pair, then add the object to the list.

Output:

[{ Jane, 21 }, { Mary, 34 }, { Peter, 40 }]

Using Iterable forEach() method

We can also convert a Dart Map to List using Iterable forEach() method instead.

Example code:

map.entries.forEach((e) => list.add(Customer(e.key, e.value)));

Just apply forEach() to entries property of the map.

Output:

print(list);
[{ Jane, 21 }, { Mary, 34 }, { Peter, 40 }]

Using Iterable map() method

Code Sample:

list = map.entries.map((e) => Customer(e.key, e.value)).toList();
print(list);

Each entry item of Dart Map’s entries is mapped to a Customer object:
– an entry.key will be customer.name
– and an entry.value as customer.age

Then using toList() method to convert the Iterable to List.

Output:

[{ Jane, 21 }, { Mary, 34 }, { Peter, 40 }]

Related posts

Related posts:


More about DartMap: Dart Map

Leave a Reply

Your email address will not be published. Required fields are marked *