if for example i had a map
{ 'id': 1, 'name': 'John' }
and I want to assign map values to class properties: Map keys are the properties and map values are the values for properties.
My Code :
class Person {
late int id;
late String name;
Person.fromJson(Map<dynamic, dynamic> json) {
// Solution 1
id = json['id'];
name = json['name'];
// I want a better solution
for (var key in json.keys) {
print('${key} - ${json[key]}');
// id - 1
// name - John
// this[key] = json[key]; ?
// HOW CAN I DO THIS?
}
}
}
void main() {
Person p = Person.fromJson({
'id': 1,
'name': 'John',
});
print('${p.id} - ${p.name}');
}
``
2
Answers
You can use the
factory
constructors in this case, but first, you need to declare the class default constructor, so we will create an instance of that class constructor from thefactory
one, using theMap<String, dynamic>
:and now you can use the
Person.fromJson()
as you expect in your code:Manually writing out the toJson/fromJson methods is time consuming and not scalable. I would recommend using json_serializable and json_annotation.
To do this, you simply create your class with the final properties you want and annotate it with @JsonSerializable()
Then just run the build command and everything will be generated for you.
flutter packages pub run build_runner build --delete-conflicting-outputs