Flutter: Loops: do-while
The do-while loop executes a code block once and then will execute it again as long as the given condition is true. The syntax is the following:
do{
// code that will be executed at least once
} while ( condition );
Let's write a program to print the numbers from one to ten using a do-while loop. The flowchart using a do-while loop is:
![The do-while loop](/_next/image?url=https%3A%2F%2Ffirebasestorage.googleapis.com%2Fv0%2Fb%2Fyayo-code-blog-prod.appspot.com%2Fo%2Flocales%252Fen%252Fposts%252FIgFPSTuDUgTrTa2wVkki%252F913cc10d-cbf4-4939-a920-cfd32bd1d54b.png%3Falt%3Dmedia%26token%3D8ebc8ff1-b0d8-4006-ad7a-3093891a504e&w=800&q=75)
The do-while loop
- We start with a variable i with initial value of 1:
var i = 1
- We will print the value of i then we will increase it by one using ++:
print( i++ )
- We will loop as long as as i is less or equals to 10:
i <= 10
Let's run the code in DartPad:
Use a do-while loop to iterate a list
We can also use a do-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 do-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 access the item in the list, print it, then increase the value of i by one:
print(cars[i++])
- We will loop as long as i is less than the list length:
i < cars.length
Let's see the code in DartPad: