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

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.


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

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>();

Tags:

Dart

Flutter