Dart Convert Map to List & List to Map
In this post we are going to learn convert Map to List and List to Map in Dart/Flutter. What is List in Dart? Dart represents arrays in the form of List objects. A List is simply an ordered group of objects List is classified in two ways What is Map? The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection Map can be classified as below Let's check Suppose we have a class called User Now let's convert List<User> into Map and vice versa Let's initialize Map We will convert this Now we convert our Map to List above using user_map.forEach((k, v) => user_list.add(User(k, v))); In the code above, we create a new Output: [{ User1, 23 }, { User2, 27 }, { User3, 25 }] We can also convert a Dart Map to List using Iterable user_map.entries.forEach((e) => user_list.add(User(e.key, e.value))); Output: [{ User1, 23 }, { User2, 27 }, { User3, 25 }] Another way to convert Map to a Dart List is to use Iterable map() method Each entry item of Map’s Output: [{ User1, 23 }, { User2, 27 }, { User3, 25 }] Now Let's create a List with User Info We convert We can convert Dart List to Map in another way: Read More about
class User {
String name;
int age;
User(this.name, this.age);
@override
String toString() {
return '{ ${this.name}, ${this.age} }';
}
}
Convert Map to List in Dart/Flutter
Map user_map = {'User1': 23, 'User2': 27, 'User3': 25};
Map
to List<Customer>
with Customer.name
from a key and Customer.age
from a value.
Before that, initialize an empty list first
var user_list = [];
Using Map forEach() method
forEach()
method
print(user_list);User
object from each key-value pair, then add the object to the user_list
.
Using Iterable forEach() method
forEach()
method instead.
print(user_list);
Using Iterable map() method
user_list
= map.entries.map((e) => User(e.key, e.value)).toList();
print(
user_list);
entries
will be mapped to a User object with entry.key
as user.name
and entry.value
as user.age
.
Then we convert the Iterable
result to List
using toList()
method
Convert List to Map in Dart/Flutter
List list = [];
list.add(User('User1', 23));
list.add(User('User2', 27));
list.add(User('User3', 25));
Using Map.fromIterable()
List<User>
into Map
using fromIterable()
constructor
var map1 = Map.fromIterable(list, key: (e) => e.name, value: (e) => e.age);
print(map1);
Using Iterable forEach() method
forEach()
method
var map = {};
list.forEach((user) => map[user.name] = user.age);
print(map);
2138 Views