How to convert an Object
type to a Map
or a List of Maps
in Dart, so the variables become key/value pairs?
Using Iterable forEach() method We can convert Dart List of Objects to Map in another way: forEach() method. var map = {}; list. forEach((customer) => map[customer.name] = {'email': customer.
You can try this: var data = { "key1": "value1", "key2": "value2", "key3": "value3", }; var myMap = Map<String, dynamic>. from(data); print(myMap); With dynamic in Map<String, dynamic> we can have the values of the map of any type.
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.
Based on my experience, dart does not provide that kind of system yet. So, basically we create function like toMap()
that manually convert the object to a key-value pair of map.
For example:
class Human { String name; int age; Map<String, dynamic> toMap() { return { 'name': name, 'age': age, }; } }
So, later when you have a Human
object, you just can call human.tomap()
.
I do this in most of my entity classes.
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