Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Class object to data structure `Map` or a `List of Maps` in Dart?

Tags:

flutter

dart

How to convert an Object type to a Map or a List of Maps in Dart, so the variables become key/value pairs?

like image 283
devashish-patel Avatar asked Mar 01 '19 16:03

devashish-patel


People also ask

How do you turn an object into a dart map?

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.

How do you change an object to a map in Flutter?

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.

What's the difference between a list and a map in Dart Flutter?

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.

What is map () in Dart?

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.


1 Answers

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.

like image 130
Haqqi Avatar answered Sep 28 '22 07:09

Haqqi