A while loop is a control structure that allows us to repeat a number of operations multiple times. In contrast to a for loop the while loop takes only a condition and repeats as long as the condition holds.

Standard While loop

The standard while loop in Dart looks similar to while loops in most other popular languages such as Java.

Here is the structure:

while (condition) {
  statements;
}

Here is an example:

var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var i = 0;
while (i < list.length) {
  print('${list[i]}');
  i++;
}

In this example the while loop will execute its content ten times. On the 11th run i will be 10 and the boolean expression will produce false, so the loop will stop.

Do-While Loop

The do while loop is also commonly known from other programming languages. The syntax in dart looks like:

do {
  statement;
 } while (condition);

Here is an example which will do exactly the same thing as the standard while loop:

var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var i = 0;
do {
   print('${list[i]}');
   i++;
} while (i < 10);

So what is the different now? In contrast to standard while loop the Do-While loop first executes the statements and check the condition afterwards. In this example this does not change anything but consider the following examples:

var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var i = 0;
while (i < 0) {
  print('${list[i]}');
  i++;
}
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var i = 0;
do {
  print('${list[i]}');
  i++;
} while (i < 0);

The example are the same as the previous ones. The only difference is that the condition has changed and checks if i < 0. In the first example where normal while loop is used, the condition does not hold and so the body of the loop is never executed. When using the Do-While loop the body is execute once before the condition will be checked and the loop will stop.

Break and continue

Like in most other popular programming languages the keywords break and continue can be used. While continue stops the current loop cycle and continues with the next one, break will stop the whole loop.

Labels

Labels can be used to break or continue While and Do-While Loops the same way as they can be for For loops. A small example:

label:
while (true) {
  print('hello');
  break label;
}