for
The for loop is one of the most common loops in Dart and probably in other programming languages. It allows us to execute a code block repeatedly. In Dart, we have different kinds of for loops:
- for loop
- for-in loop
The for loop
The classic for loop allows us to execute a code block as long as the given condition is true. The syntax is:
for (initialization; condition; statement) {
// code that will be executed
}
- initialization: Will be executed only one time. Usually, we will initialize a helper variable that we will use to iterate inside the for loop.
- condition: The code block inside the for loop will be executed as long as this condition is true.
- statement: Will be executed every time after the code block. Usually, it is here where we will increase the value of the variable created on the initialization.
Let's write a program to print the numbers from one to ten using a for loop. The flowchart using a for loop is:
- Initialization: we create a variable i with an initial value of 1:
var i = 1
- Condition: We will loop as long as i is less or equals to 10:
i <= 10
- We will print the value of i:
print( i++ )
- Statement: We will increase the value of i by one using ++:
i++
Let's run the code in DartPad:
Use a for loop to iterate a list
We can also use a for loop to iterate each element in a list. Let's write a program to learn how to do it.
Given the next list of cars:
var cars = ['Toyota', 'Mazda', 'Nissan'];
We want to print each of them using a for loop. What do we have to do?
- On the initialization, we create a variable with an initial value of 0 because the first position in a list is at the index 0:
var i = 0
- On the condition, we will check if i is less than the list lenght:
i < cars.length
, we will loop as long as this condition is true. - On the statement, we will increase the value of i by one:
i++
.
Let's see the code in DartPad:
The for-in loop
The for-in loop is used to iterate through elements of collections like the list. It is very common to use the for-in loop when we want to iterate a list and do not want to know the element index.
The syntax is:
for(var item in list) {
// code that will be executed
}
- list: Is the list that we want to iterate
- item: Each item of the list is assigned to this variable
Let's write a program in DartPad to iterate the list of cars from the previous example: