All about Maps
In Flutter and Dart Map is a Collection. Collection contians data in key value pair.
Map and List are one of the most foundamentals for Dart programming language and if you want to learn Flutter well, you must master Map and List. Later down the road we will also cover Dart nested Map.
Map could be used for basic data manupulation, routing and sqflite data storage.
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 a pair.
But Dart Map is still different JSON object.
In the above example name
, age
and country
are our keys and Dastagir Ahmed
, 34
and Bangladesh
are our values.
So Map in Dart is the same. So what does Map do 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.
There are at least three different ways to create Map object in Flutter.
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
From the code below, if you see the first line carefully, you will see that we have used Map()
constructor to create an object called mapObj2
.
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}
This is exaclty the same as the first way and printed results are same and wrapped in curly braces. It's very important to notice.
Third way Map
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.
Dart keys could be String and int, but JSON keys are only String.
For values we have used dynamic type
since they could be integer, String or even object type. Of course for values you can use any specific type if you are pretty sure about data format.
And see the printed value
{name: Dastagir Ahmed, age: 34, country: Bangladesh}
To access them you can use with the keyword keys
or you can explicitly mention the keys
if you want to retrieve any specific value for a key.
print(mapObj1.keys);
print(mapObj2.keys);
print(mapObj3.keys);
Here in the above code we say that, print the values for all the keys
. When you use dot (.) keys
, it means for all the keys get me the values. 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}
print(mapObj1["name"]);
print(mapObj2["age"]);
print(mapObj3["country"]);
In the above code, we used ["key name"]
to explicitly mention the keys.
The results are
Dastagir Ahmed
34
Bangladesh
Dart Map forEach method
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);
});
See how we specificly printed the keys.
Map's forEach function is used a lot in actual app dev. If you retreive server data, you do as JSON format. This JSON data may need to loop through and process further. In that case forEach comes to rescue you.
So Map object allows you to access them using forEach but it also has 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 the Map iterable. Otherwise it won't work. With entries if we use the map() function, then we get something that is not iterable. It means you can not loop or go through one by one.
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();
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
You can create a class model and declare a Map based on that class object.
class Category {
final String name;
final Color color;
Category(this.name, this.color);
}
Here Category
is a 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 value pair are object and boolean. See the practical example how to use Map
All About Lists
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 not access them using index, but you can do it with List.
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 retrieve 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,
};
}
}
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 any data. Do remember you must insert data in it.
Let's use the below method to convert the map to list of objects.
List items =
_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 contain the value not the key.
And since Map functions return iterables(not indexable), we are converting the Map into a List using toList().
void main() {
var cartItem1 = CartItem(1, 10);
var cartItem2 = CartItem(2, 100);
var cartItem3 = CartItem(3, 20);
Map<int, CartItem> _items =
{
1: cartItem1,
2: cartItem2,
3: cartItem3
};
List items =
_items.entries.map((e){
return e.value;
}).toList();
print(items[2].price);
}
class CartItem {
int id;
int price;
CartItem(this.id, this.price);
}
var map1={
1:"string1",
2:"string2",
3:"string3"
};
myList()=> map1.entries.map((e)=>e.key).toList();
print(myList().length);
The above example is a very foundamental example of Dart Map converts to List. It's used a lot during complex data processing which comes from server side as JSON format.
var value = map1.values.toList();
var key = map1.keys.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();
List of Maps
Here I will see what is List of Maps? If you have many maps and if you put them inside a List, then we say it a List of Maps. Let's see how it looks like
Here we see [] and we also see {}. We know that {} refers to Map. We have a lot of {} inside []. We know [] refers to List.
So this is called List of Maps. Since there are many maps, we call it List of Maps.
Here we opened up the first Map, and we see there is more maps. So there could be a map inside a map.
Here we created a variable called ticketList. We can use ticketList to access the values of the keys.
We will access like this ticketList["from"]["name"], then this will give us the value New-York. We can use ticketList["flying_time"] is '8H 30H'.
More about Dart Map and List
2024-11-02 06:07:52
Mistake in "Second way using Map() constructor" You created an object with the name of "mapObj2", But you assigned the values with "mapObj" See: mapObj["name"]="Dastagir Ahmed"; mapObj["age"]=34; mapObj["country"]="Bangladesh"; Please correct it