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.