How do you convert a List into a Map in Dart?

In Dart, you can convert a List into a Map using the Map.fromIterable() constructor or by iterating over the List and manually adding elements to the Map.

1. Using Map.fromIterable(): The Map.fromIterable() constructor creates a new Map from an iterable, such as a List. You need to specify the key and value selectors that define how the keys and values are extracted from the List elements.

Syntax:

Map<K, V> Map.fromIterable(Iterable iterable,
    {K key(key), V value(value)});

Example:

void main() {
  List<String> fruits = ['apple', 'banana', 'orange'];

  // Using Map.fromIterable
  Map<String, int> fruitMap = Map.fromIterable(fruits, key: (item) => item, value: (item) => item.length);
  print(fruitMap); // Output: {apple: 5, banana: 6, orange: 6}
}

2. Manually Iterating and Adding Elements: You can also manually iterate over the List and add elements to the Map using a loop or any other mechanism.

Example:

void main() {
  List<String> fruits = ['apple', 'banana', 'orange'];
  Map<String, int> fruitMap = {};

  // Manually converting List to Map
  for (String fruit in fruits) {
    fruitMap[fruit] = fruit.length;
  }

  print(fruitMap); // Output: {apple: 5, banana: 6, orange: 6}
}

Both methods will give you the same output, where the List fruits is converted into a Map where each fruit is a key, and its length is the corresponding value. You can customize the conversion based on your requirements by adjusting the key and value selectors.

Keep in mind that when converting a List to a Map, the keys in the resulting Map should be unique. If there are duplicate keys in the List, the last occurrence will overwrite the previous ones in the Map.

error: Content is protected !!