I looking for an on-the-shelf way to convert a List into a Map in Dart.
In python for example you can do:
l= [ ('a',(1,2)), ('b',(2,3)), ('c',(3,4) ) ] d=dict(l) ==> {'a': (1, 2), 'c': (3, 4), 'b': (2, 3)}
The dict function expects a List of couple. For each couple, the first element is used as the key and the second as the data.
In Dart I saw the following method for a List : asMap(), but it's not doing what i expect: it use the list index as key. My questions:
Proposal:
List.toMap() //same as python dict. List.toMap( (value) => [ value[0], value[1] ] ) //Using anonymous function to return a key and a value from a list item.
Thanks and Regards,
Nicolas
We can convert Dart List to Map in another way: forEach() method. var map2 = {}; list. forEach((customer) => map2[customer.name] = customer.
List, Set, Queue are iterable while Maps are not. Iterable collections can be changed i.e. their items can be modified, add, remove, can be accessed sequentially. The map doesn't extend iterable.
Dart Map is an object that stores data in the form of a key-value pair. Each value is associated with its key, and it is used to access its corresponding value. Both keys and values can be any type. In Dart Map, each key must be unique, but the same value can occur multiple times.
You can use Map.fromIterable:
var result = Map.fromIterable(l, key: (v) => v[0], value: (v) => v[1]);
or collection-for (starting from Dart 2.3):
var result = { for (var v in l) v[0]: v[1] };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With