Dart: Convert Class Instances (Objects) to Maps and Vice Versa

Updated: January 13, 2023 By: A Goodman Post a comment

This article walks you through a few examples of converting a class instance (object) into a map and vice versa in Dart (and Flutter as well). Learning through examples is the best way to deepen understanding and long-term memory. Without any further ado, let’s get started!

Converting a Dart Object to a Map

At the time of writing, there are no built-in functions that can help us convert a class instance into a map for all cases. Therefore, we have to write code for each specific case. However, this isn’t a hard task.

Whenever defining a class, you can add a toMap() method like this:

class MyClass {
   /*...*/

   // the toMap() method
   Map<String, dynamic> toMap(){
     return {
       "property1": property1,
       "property2": property2,
       // and so on
     }
   }
}

Example

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

  Person(this.name, 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 john = Person('John Doe', 36);
  // Get map with key/value pairs by using the toMap() method
  final johnMap = john.toMap();
  print(johnMap);
}

Output:

{name: John Doe, age: 36}

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, so we have to write some lines of code to get the job done. All you need to do is to connect each property of the class to the corresponding value of the map.

Example

// Define Product class
class Product {
  final String name;
  final double price;
  final double? weight;

  Product({required this.name, required this.price, this.weight});
}

void main() {
  final Map<String, dynamic> map1 = {
    "name": "A big water melon",
    "price": 1.99,
    "weight": 3.5
  };
  final Product product1 =
      Product(name: map1['name'], price: map1['price'], weight: map1['weight']);
  print(product1.runtimeType);

  final Map<String, dynamic> map2 = {"name": "Banana", "price": 0.99};
  final Product product2 = Product(name: map2['name'], price: map2['price']);
  print(product2);
}

Output:

Product
Instance of 'Product'

Conclusion

You’ve learned how to turn an object into a map and vice versa in Dart. This knowledge might be extremely helpful when you working with databases or communicating with network APIs. If you would like to explore more new and wonderful stuff about Dart and Flutter, take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles