Create class with toMap functionality in Dart


Map

Many inbuild dynamic types in Dart/Flutter have a toMap method which can be helpful when you need a map the class (Map store value as key value pair, like Json data). Let’s learn how to add such a method for our class

Create a class with few members first

class Kart {
 String itemName;
 Pref manuFacturer;
 double qty;
 DateTime expDate;
}

ToMap

Now add a toMap method to our Product class

class Product {
 String itemName;
 String manuFacturer;
 double qty;
 DateTime expDate;    
   
 Map<String, dynamic> toMap() {
   return {
     'item': itemName,
     'mfr': manuFacturer,
     'qty': qty,
     'expDate': expDate
  };
}

Class is ready for use lets create a instance of class and make a call to Map type.

var newProduct=new Product('Honey','Nature Products',10,12\12\2023);

//Let’s make a call to toMap()

Map<String, dynamic> map =
   newProduct.toMap();

Map is required when deal with Nosql data, on firebase or Mongo like databases. So we have to manually add Json structure each time when we pass values, or add functionality with a model class like the above one. I think this might helpful for new users.

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.