How do you convert a List into a Map in Dart?
How do you convert a List into a Map in Dart?
Here's how you can convert a List into a Map in Dart:
To convert a List into a Map in Dart, you can use the asMap() method or the Map.fromEntries() constructor. Here's how each method works:
asMap()The asMap() method returns a Map view of the List. It maps the indices of the List to the corresponding elements. Here's an example:
List<String> fruits = ['apple', 'banana', 'cherry'];
Map<int, String> fruitsMap = fruits.asMap();
print(fruitsMap);
// Output: {0: apple, 1: banana, 2: cherry}
In this example, the asMap() method is called on the fruits List, and the resulting Map maps the indices (0, 1, 2) to the corresponding elements ('apple', 'banana', 'cherry').
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.