Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
communitycreator

How to convert a list to a map in Dart

Maria Elijah

Overview

Dart provides methods to convert a list to a map, including:

  • Map.fromIterable()
  • orEach()

Map.fromIterable()

The fromIterable() method is used to create an instance of a Map from an iterable.

Let’s assume we have a class model:

class Student{
  String id;
  String name;

  Student(this.id, this.name);
}

We can convert List<Student> into Map, where:

  • key: id
  • value: name

Example

// Student's list
[{ 15GH1239, Maria}, { 15GH1243, Paul}, { 15GH1009, Jane}]

//Now to Map

// Map { id:name }
{15GH1239: Maria, 15GH1243: Paul, 15GH1009: Jane}

Let’s implement this example by writing a program to convert a list to a map.

class Student{
  String id;
  String name;

  Student(this.id, this.name);


 
}

void main(){
  // Create a list
  List myList = [];
  myList.add(Student('15GH1239', 'Maria'));
  myList.add(Student('15GH1243', 'Paul'));
  myList.add(Student('15GH1009', 'Jane'));
  
  // Convert the list to a map
  // Using fromIterable()
  
  var map1 = Map.fromIterable(myList, key: (e) => e.id, value: (e) => e.name);
  print(map1);
}

Explanation

We create a class named Student with attributes id and name. Next, we use the class’s attributes to create a new list named *myList. Finally, we use Map.fromIterable() to convert the list to a map.

In the method for the first argument, we pass myList as an iterable. The method then calculates the key and value for each element of the iterable.

forEach()

The forEach() method iterates over an iterable such as a list.

The following code uses the same class and list as the previous example to demonstrate how to convert a list to a map.

class Student{
  String id;
  String name;

  Student(this.id, this.name);
 
}

void main(){
  // Create a list
  List myList = [];
  myList.add(Student('15GH1239', 'Maria'));
  myList.add(Student('15GH1243', 'Paul'));
  myList.add(Student('15GH1009', 'Jane'));
  
  // Convert the list to a map
  // Using forEach()
  var map1 = {};
  myList.forEach((Student) => map1[Student.id] = Student.name);
  print(map1);
}

Explanation

We use the forEach() method in line 19 to iterate through the list and add an entry (key, value) to the Map for each item in the list.

RELATED TAGS

dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring