How to convert an Object
type to a Map
or a List of Maps
in Dart, so the variables become key/value pairs?
5 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.
-
-
4he is using dynamic because value might be a string or integer or boolean. declaring dynamic type will assign the type of variable during the run time Feb 26, 2020 at 14:37
-
-
@OunknownO Nope. Just do
Map<String, dynamic> humanMap = yourHumanObj.toMap()
Jan 6, 2021 at 4:49 -
@OunknownO - Basically you can also write
toMap
method as a getter. In that case, you would sayyourHumanObj.toMap
Jan 6, 2021 at 4:52
This is a much easier and error-prone-free approach, (And if you are already using these classes as DTO objects that need to be serialized this is a double win).
Add the following 3 dependenciess in your pubsec.yaml
dependencies:
flutter:
sdk: flutter
json_annotation:^3.1.1
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^1.10.11
json_serializable: ^3.2.5
In the class that you want to get the Map for do the following.
part 'person.g.dart';
@JsonSerializable(explicitToJson: true)
class Person{
String name;
String surname;
Person(this.name,this.surname);
//make sure you have the (Just change part of the method name to your class name)
factory Person.fromJson(Map<String, dynamic> json) =>
_$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);//Replace 'Person' with your class name
}
That's it, you then just have to run the following command in your terminal so flutter can generate the "toMap()" method for you.
flutter pub run build_runner build --delete-conflicting-outputs
Then use it like such.
var person =Person('somename','some surname');//This is object
Map personMap =person.toJson();
Ez. This is a much better approach especially if you have complex objects with multiple objects inside. Just make sure that each nested object contains these changes as well (JsonSerializable annotation, the 'part 'class.g.dart'' , and the 2 methods)
NOTE: that if property changes are made to the classes, just run this command again.
flutter pub run build_runner build --delete-conflicting-outputs
-
1
You can check out this package class_to_map
import 'package:class_to_map/class_to_map.dart';
class Test {
String val1 = "value 1";
int val2 = 2;
Map val3 = {"a": "another value"};
}
print(Test().toMap());
// converting map to class
{"val1": 'value 1', "val2": 2, "val3": {"a": "another value"} }.toClass<Test>();
-
is this method will refer the changes to other files also? eg: i change the file here (converting to map, change the value, converting it back to class), would that affect if i cal this class elsewhere? Nov 29, 2021 at 9:05
-
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. In the example above, it is String.
-
2This converts a map to a map, not an object (non-class instance) to a map Nov 14, 2020 at 19:31
-
var keyValuePair = {'name' : Object.name, 'surname':Object.surname};
That will give you a Map object.
var listOfMaps = List<Map<String, dynamic>>();
listOfMaps.Add({'name' : Object.name, 'surname':Object.surname});
That will give you a list of maps
json.encode(...)
creates the actual JSON string from Maps)