Dart map() function explanation with example

Dart map() function explanation with example:

In this post, we will learn how to use map() function with examples. map() function is used to map over the items of a list one by one.

We can pass one function to map() and calls that function on each element of the list. It returns one lazy iterable.

This method returns a view of the mapped elements. The supplied function will be invoked only once the iterable is iterated.

It doesn’t keep or cached the iterable items. Each time we are iterating over the returned iterable multiple times, it will be called multiple times.

Let’s check it with different examples:

Example 1: Change the list to square of each value:

Let’s take a look at the below program:

void main() {
  var items = [1,2,3,4,5];
  var newItems = items.map((e) => e*e);
  
  for(var e in newItems){
    print(e);
  }
}

Here, the function we are passing to map returns the square value for each. If you run it, it will print the below output:

1
4
9
16
25

As you can see here, all numbers are changed to square.

Example 2: map() and create a list:

Since the return value of map is a lazy iterable, we can also convert it to a list by calling toList method.

For example:

void main() {
  var items = [1,2,3,4,5];
  var newItems = items.map((e) => e*e).toList();
  
  print(newItems);
}

It will print:

[1, 4, 9, 16, 25]

dart map method example

You might also like: