For Loop, For Each Loop And Map In Dart

As the title suggests, in this post we will learn about various options for looping over collections in Dart. Specifically, we learn to use for,forEach and map in Dart.

Introduction

When working in any application, you quickly come across the need to work with collection of data. It can be a collection of simple strings and integers or a collection of complex data type.

You might want to iterate over the list to show it your List in a Flutter app. Or you want to update value of certain item in the list.

DecisionMentor app

So, in this post, we will learn to do just that.

Setup Car Collection

Let’s say we have a collection of cars that we are working with.

A simple class for Car:

class Car {
  Car(this.name, this.isElectric);  
  final String name;
  final bool isElectric;
}

Learn More About Class: A Class In Dart

Our car object has a name and an identifier isElectric to represent whether it is an electric car or not.

We now initialize a collection of car objects below with name and isElectric values.

void main() {
	var car1 = Car("Ford", false);
	var car2 = Car("Toyota", false);
	var car3 = Car("Honda", false);
	var car4 = Car("Tezla", false);

	var ls = [car1, car2, car3, car4];
}

Our collection is now ready.

Tip: You can try out the Dart codes in DartPad.

For Loop, For Each Loop And Map In Dart
For, For Each And Map In Dart

How To Write For Loop In Dart

We start with the most ubiquitous type of iteration in programming i.e. the for loop. In Dart, we create a for loop with this syntax:

for(var i = 0; i< ls.length; i++) {
    print("${ls[i].name} is electric? ${ls[i].isElectric}");
  }

The loop starts from i = 0 and iterates until the value of i is smaller than the ls.length. After each iteration, the value of is incremented by 1.

The output from above code is:

Ford is electric? false
Toyota is electric? false
Honda is electric? false
Tezla is electric? true

For Each Loop In Dart

Another type of loop in Dart is the forEach loop. It is pretty much same as the for loop but with one distinction.

Difference between For Loop And For Each Loop

The difference between for loop and forEach loop in Dart is that with the for loop you get access to the index of current iteration (i).

So, if you are not interested in the current index of iteration, then you can use the forEach loop.

Understanding For Each Loop Syntax

The syntax for forEach loop is smaller and prettier than the for loop.

void forEach(void f(E element)) {

The forEach loop can be used with any type of collection. This loop iterates over each element of the collection and applies the function for each item.

The parameter of the function is the type of collection that we are working with.

For example if the collection is a list of String then the function takes String value as parameter. Similarly, if the collection is of Car objects, then the function takes Car as argument.

Different Ways To Write forEach Loop

We can write the forEach loop in many different ways. We can use anonymous functions or defined functions.

Anonymous Function 1

ls.forEach((car) => print("${car.name} is electric? ${car.isElectric}"));

Anonymous Function 1

ls.forEach((Car car) {
	print("${car.name} is electric? ${car.isElectric}");
});

Defined Function

doSmth(Car car) {
  print("${car.name} is electric? ${car.isElectric}");
}

ls.forEach(doSmth);

Map Function In Dart

Another useful function when working with collections in Dart is the map function.

The map function is similar to the forEach loop with one major distinction.

Find Remote Flutter Jobs

Difference Between Map And For Each Loop

Although both map and forEach looks similar syntactically, the key difference between these two is that the map function returns the object after iteration.

So, this allows the map function to update the collection of items while it is being looped over and create new updated collection.

Using Map On Iterable Collection

Let’s see the map function in action.

We want to update the car collection so that the car named Tezla is renamed to Tesla.

var lss = ls.map((car) {    
    if(car.name == "Tezla") {
      print('upating ${car.name}...');
      car.name = "Tesla";
    }    
    return car;
  });
  
  //loop over mapped object collection
  lss.forEach((car) => print("${car.name} is electric? ${car.isElectric}"));

If you run the code now, you will see the collection items has been updated in the new collection lss.

Ford is electric? false
Toyota is electric? false
Honda is electric? false
upating Tezla...
Tesla is electric? true

Wrapping Up For, ForEach And Map In Dart

This was an introduction to different types of collection iteration options available in Dart. We looked at the for, forEach and map functions and also the differences between them.

Stay tuned to learn more about other ways to iterate over a loop like the while loop and for in loop and other useful functions when working with collection in Dart.

Also, don’t forget to checkout our articles on Flutter!