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

The while loop

  1. We start with a variable i with initial value of 1: var i = 1
  2. We will loop as long as as i is less or equals to 10: i <= 10
  3. 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?

  1. 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
  2. We will loop as long as i is less than the list length: i < cars.length
  3. 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:

Share this article