How To Convert Class Instances (Objects) to Maps and Vice Versa In Dart

In this article, we are going to convert the class object to the map in dart by taking a different example which is given below.

Converting a Dart Object to a Map

// Define Person class
class Person {
  // properties
  final String name;
  final int age;

  Person(, this.age);

  // Implement a method that returns the map you need
  Map<String, dynamic> toMap() {
    return {"name": name, "age": age};

void main() {
  // Create a new person instance
  final data = Person('Sagar Koju', 24);
  // Get map with key/value pairs by using the toMap() method
  final dataMap = data.toMap();

Here we have defined the class Person which takes two parameters name and age and we pass them to the constructor. and we have implemented the method of the map i.e toMap(). In the toMap we take the saved values in our local variables and that return a Map.


{name: Sagar Koju, age: 24}

Converting a Map to a Class Instance

Currently, there is no built-in function that can help us turn a map into a class instance. All we need to do is to connect each property of the class to the corresponding value of the map.

// Define Product class
class ProductItem {
  final String name;
  final int price;
  final int weight;

  ProductItem({required, required this.price, required this.weight});

void main() {
  Map<String, dynamic> map1 = {
    "name": "Apple",
    "price": 2,
    "weight": 3,
  ProductItem product1 = ProductItem(
      name: map1['name'], price: map1['price'], weight: map1['weight']);

  Map<String, dynamic> map2 = {"name": "Banana", "price": 1, 'weight': 4};
  ProductItem product2 = ProductItem(
      name: map2['name'], price: map2['price'], weight: map2['weight']);

We will convert this Map<String, dynamic> to ProductItem object with namepriceweight value from Map values. It is easy, we only need to use the class constructor method and pass map[key] as the value.


Instance of 'ProductItem'
Instance of 'ProductItem'

Hence we’ve known how to convert an Object to Map in Dart, and vice versa.