Flutter: Loops: while
The while loop executes a code block as long as the given condition is true. The syntax is the following:
while( condition ){
// code that will be executed
}
Let's write a program to print the numbers from one to ten using a while loop. The flowchart using a while loop is:
The while loop
- We start with a variable i with initial value of 1:
var i = 1
- We will loop as long as as i is less or equals to 10:
i <= 10
- We will print the value of i then we will increase it by one using ++:
print( i++ )
Let's run the code in DartPad:
Use a while loop to iterate a list
We can also use a while 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 while loop. What do we have to do?
- We need a variable with an initial value of 0 because the first position in a list is at the index 0:
var i = 0
- We will loop as long as i is less than the list length:
i < cars.length
- We will access the item in the list, print it, then increase the value of i by one:
print(cars[i++])
Let's see the code in DartPad: