Understanding Dart Map and List for Flutter Development

All About Map

In flutter and dart Map is a collection. It contians data like below

Map and List are one most the most foundamentals for dart programming and if you want to learn flutter well, you must master Map and List.

Map could be used from basic data manupulation, routing and sqflite data storage.

{
"name":"Dastagir Ahmed",
"age":34,
"country":"Bangladesh"
}

If you see the carefully, you will see that, it exactly look like json format in Javascript. 

If you are familiar with Javascript, it would be very easy to understand the concept. JSON format is for storing keys with values. 

In the above example name, age and country are our keys and Dastagir Ahmed, age and Bangladesh is our values. 

So Map in Dart is the same. So What Map does in dart?

Stores information (like data, object) in key and value pair

So whenever you see data with curly braces (most outer), you need to recognize it as a Map.

Creating Maps

There are at least three different ways to create Map object in flutter

First way using curly braces

var mapObj1= {
"name":"Dastagir Ahmed",
"age":34,
"country":"Bangladesh"
};

print(mapObj1);

First way is the most common way. Just wrap your data within curly braces in key and value pair. Take care of the keys in double quotation.

If you see the printed value you will see 

{name: Dastagir Ahmed, age: 34, country: Bangladesh}

As you see, printed values are also wrapped in curly braces.

Second way using Map() constructor

var mapObj2 = new Map();
mapObj["name"]="Dastagir Ahmed";
mapObj["age"]=34;
mapObj["country"]="Bangladesh";

print(mapObj2);

and if you print the result you will see 

{name: Dastagir Ahmed, age: 34, country: Bangladesh}

Which is exaclty the same the first way and printed results are same and wrapped in curly braces. It's very important to notice.

Third way Map<String dynamic> type

var mapObj3 = Map<String, dynamic>();
mapObj3["name"]="Dastagir Ahmed";
mapObj3["age"]=34;
mapObj3["country"]="Bangladesh";

print(mapObj3);

This way, you explicitly mention the data type for key and value. In our case for keys we have used string format. And keys are always in string format anyway. For values we have used dynamic type since they could be integer, string or even object type. Of course for values you can any specific type if you are pretty sure about data format.

And see the printed value

{name: Dastagir Ahmed, age: 34, country: Bangladesh}

 

Accessing Map data

To access them you can use with the keyword "keys" or you can explicitly mention the key if you want to retrieve any specific value for a key.

Using keys

print(mapObj1.keys);
print(mapObj2.keys);
print(mapObj3.keys);

and you will see the result as below

{name: Dastagir Ahmed, age: 34, country: Bangladesh}
{name: Dastagir Ahmed, age: 34, country: Bangladesh}
{name: Dastagir Ahmed, age: 34, country: Bangladesh}

Explicitly mention the keys

print(mapObj1["name"]);
print(mapObj2["age"]);
print(mapObj3["country"]);

The results are 

Dastagir Ahmed
34
Bangladesh

 

There are other ways to access them. You can use forEach method to access the keys. See the example below

  mapObj1.forEach((key, value){
    print(key);
  });
  
// notice the entries property
  mapObj1.entries.forEach((entry){
    print(entry.key);
  });

So map object allows you to access them using forEach but it has also varieties. As you can see it's entries property as well.

The result is 

name
age
country

 

You can use them to access the values as well. See the example below

  mapObj1.forEach((key, value){
    print(value);
  });
  
// notice the entries property
  mapObj1.entries.forEach((entry){
    print(entry.value);
  });

The result is

Dastagir Ahmed
34
Bangladesh

 

You can also access them using .map method

mapObj1.entries.map((entry){
 print(entry);
}).toList();

If you use .map method you must need to use .toList() to make map iterable. Otherwise it won't work. Anyway, the printed result is 

MapEntry(name: Dastagir Ahmed)
MapEntry(age: 36)
MapEntry(country: Bangladesh)

At the same time you can use the key or value to retrieve keys and values

mapObj1.entries.map((entry){
 print(entry.key);
 print(entry.value);
}).toList();

Accessing using index

You can also access data by index. To do that, you would do like below

mapObj1.keys.elementAt(0);
//print 
print(mapObj1.keys.elementAt(0));

It will print "name" on the console for the keys. You can also access the value using elementAt. 

mapObj1.values.elementAt(0);
//print 
print(mapObj1.values.elementAt(0));

It will print Dastagir Ahmed on the console.

Do the E-commerce project to master Dart & Flutter

 

Delcare map of objects

You can create a class model and declare map based on that class object.

class Category {
  final String name;
  final Color color;

  Category(this.name, this.color);
}

Here category is class, which has two properties name and color. 

Now we can create a map based on that. This map also would be in key and pair value. 

 var _categories = {
    Category("Apple", Colors.red): false,
    Category("Orange", Colors.orange): false,
    Category("Banana", Colors.yellow): false,
  }

Here _categories is a map and it's key and pair are object and boolean. See the practical Example how to use map

 

All About List

List has a special trait. Lists are wrapped with third brackets or the square brackets. See an example below

var ageList = ["35", "39", "27"];

And if you do 

print(ageList);

You will get

[35, 39, 27]

You can access them individually by index. That's very different from Map. In Map object, you can access them using index.

For the list object you can do 

print(ageList[0]);
print(ageList[1]);
print(ageList[2]);

And you will get 35, 39, 27

 

If you have a model which creates objects for your application and stores in the database, you need to convert to Map or JSON object before you save them into the database.

Otherwise you won't be able to retreive information from object.  

If your model is responsible for creating data object, then you should have a method, that converts that data info Map format (like key and value pair)

class User{
  
  String name;
  int age;
  String location;
  
  User(this.name, this.age, this.location);
  
  Map<String, dynamic> toJson(){
    return {
      "name":name,
      "age":age,
      "location":location,
    };
  }
}

 

Convert a Map to List of Objects

If you have a map of objects, and you want to convert them to a list of objects look at the following example. See our map 

Map<int, CartItem> _items={
1:CartItem1,
2:CartItem2,
3:CartItem3
};

Here _items stores CartItem, and it is simply a model. You can make your model based on anything data. Do remember you must insert data in it. 

Let's use the below method to convert the map to list of objects.

List<CartItem> get getCarts{
    return _items.entries.map((e){
       return e.value;
     }).toList();

}

Here we are grabbing the _items map and using map function of it and then we are just returning the value of it. List should only conltain the value not the key.

And since map functions return iterables, we are converting it into a List using toList().

Convert to List using entries.map()

 var map1={
   1:"string1",
   2:"string2",
   3:"string3"
 };

  myList()=> map1.entries.map((e)=>e.key).toList();
  
  print(myList().length);

Convert to List uisng toList() method

var value  = map1.values.toList();
var key     = map1.keys.toList();

Calling .map().toList()

You call .map() on a map object. You call this because you may want to change the value of the map's key or do something using those keys and values. Once you are done you return them as a list using toList(). If you use toList() it becomes a list. If it's a list them you can access the items using index. 
So whenever you need a list from a map you would do this.
mapObject.entries.map((e)=>e.value).toList();

More about Dart Map and List

Convert a List to Map

Remove an item from List

Recent posts