Dart While Loop

A Dart while loop repeatedly executes a block of code while a specified condition remains true. It is useful when the number of required iterations is not known before the loop begins.

Dart checks the condition before each iteration. If the condition evaluates to true, the statements inside the loop run. When the condition evaluates to false, the loop stops and execution continues with the statement following the loop.

In this tutorial, you will learn the syntax and execution flow of a Dart while loop, along with examples using counters, nested loops, break, continue, and infinite loops.

Dart While Loop Syntax

The syntax of a while loop in Dart is:

</>
Copy
while (condition) {
  // statement(s)
}

The condition must evaluate to a Boolean value. The statements inside the braces execute repeatedly as long as this condition is true.

A while loop normally requires three elements:

  • Initialization: Create and initialize any variable used by the loop condition before entering the loop.
  • Condition: Check whether another iteration should run.
  • Update: Change the control variable inside the loop so that the condition can eventually become false.

If the loop does not update the values involved in its condition, it may run indefinitely.

Dart While Loop Execution Flow

The following flowchart shows how control moves through a while loop. Because the condition is checked before the loop body, a while loop may execute zero times.

Dart While Loop
  1. Dart evaluates the while-loop condition.
  2. If the condition is true, Dart executes the statements in the loop body.
  3. Control returns to the condition after the loop body finishes.
  4. The process repeats until the condition evaluates to false.
  5. Execution then continues with the first statement after the while loop.

Dart While Loop to Print Hello World Five Times

In the following program, the while loop prints 'Hello World' five times. The variable i keeps track of the number of completed iterations.

main.dart

</>
Copy
void main() {
  var i = 0;
  while (i < 5) {
    print('Hello World');
    i++;
  }
}

The loop starts with i equal to 0. After each message is printed, i++ increases the counter by one. When i reaches 5, the condition i < 5 becomes false.

Output

Hello World
Hello World
Hello World
Hello World
Hello World

Dart While Loop to Count Down from Five

A while loop can also count backward by decrementing its control variable after each iteration.

</>
Copy
void main() {
  var number = 5;

  while (number >= 1) {
    print(number);
    number--;
  }
}

The condition remains true while number is at least 1. The decrement expression number-- reduces its value after every iteration.

5
4
3
2
1

Dart Nested While Loop for Multiplication Tables

A while loop can be placed inside another while loop. This structure is called a nested while loop. The inner loop completes all of its iterations for each iteration of the outer loop.

In the following example, the outer loop selects a number from 1 through 5. The inner loop prints its first ten multiples.

main.dart

</>
Copy
import 'dart:io';

void main() {
  var i = 1;
  while (i <= 5) {
    var j = 1;
    while (j <= 10) {
      stdout.write(i * j);
      stdout.write('  ');
      j++;
    }
    stdout.write('\n');
    i++;
  }
}

The variable j is initialized inside the outer loop so that it starts again at 1 for every multiplication table.

Output

1  2  3  4  5  6  7  8  9  10  
2  4  6  8  10  12  14  16  18  20  
3  6  9  12  15  18  21  24  27  30  
4  8  12  16  20  24  28  32  36  40  
5  10  15  20  25  30  35  40  45  50  

Stopping a Dart While Loop with Break

The break statement immediately ends the nearest enclosing loop, even when the while-loop condition is still true.

In the following example, the original condition would allow the loop to continue until i reaches 10. However, the conditional break stops it when i is 4.

main.dart

</>
Copy
void main() {
  var i = 1;
  while (i <= 10) {
    print(i);
    if (i == 4) break;
    i += 1;
  }
}

Output

1
2
3
4

Skipping Dart While Loop Iterations with Continue

The continue statement skips the remaining statements in the current iteration and returns control to the while-loop condition.

The following program prints the even numbers from 1 through 10. When the current number is odd, continue skips the print statement.

main.dart

</>
Copy
void main() {
  var i = 0;
  while (i <= 10) {
    i += 1;
    if (i % 2 == 1) continue;
    print(i);
  }
}

Make sure that you update the control variables used in the while loop condition, before you execute the continue statement.

Here, i is incremented before the continue statement can run. If the increment were placed after continue, the loop could remain on the same odd value indefinitely.

Output

2
4
6
8
10

Dart Infinite While Loop

An infinite while loop has a condition that never becomes false. Such a loop continues until the program is stopped, an error occurs, or a statement such as break exits it.

main.dart

</>
Copy
void main() {
  while (true) {
    print('Hello World');
  }
}

Output

Hello World
Hello World
Hello World
Hello World

The execution prints the string 'Hello World' indefinitely. Only part of the output is provided above.

An intentional infinite loop should contain a clear exit condition when the program eventually needs to leave the loop. The following pattern uses break to stop after a condition is met.

</>
Copy
void main() {
  var count = 1;

  while (true) {
    print(count);

    if (count == 3) {
      break;
    }

    count++;
  }
}
1
2
3

Dart While Loop and Do-While Loop Difference

A Dart while loop checks its condition before executing the loop body. Therefore, it may not execute at all. A do-while loop checks its condition after the body, so its statements execute at least once.

</>
Copy
void main() {
  var value = 10;

  while (value < 5) {
    print('While loop');
  }

  do {
    print('Do-while loop');
  } while (value < 5);
}
Do-while loop

The while-loop body does not run because its condition is false at the first check. The do-while body runs once before Dart evaluates the same condition.

Common Dart While Loop Errors

  • Forgetting to update the control variable: The condition may remain true forever, creating an unintended infinite loop.
  • Updating after continue: Statements after continue do not run during that iteration, so place essential counter updates before it.
  • Using the wrong comparison: Check whether the boundary should be included before choosing between operators such as < and <=.
  • Resetting a variable inside the loop: Reinitializing the control variable during every iteration may prevent progress toward the stopping condition.
  • Using while when a counted loop is clearer: When initialization, condition, and update form a simple counter, a for loop may be easier to read.

Dart While Loop Questions

When should a while loop be used in Dart?

Use a while loop when repetition depends on a condition and the number of iterations is not known in advance. Examples include processing input until a valid value is received or repeating an operation until a search succeeds.

Can a Dart while loop execute zero times?

Yes. Dart evaluates the condition before entering the loop body. If it is false during the first check, none of the statements inside the loop execute.

How do you stop an infinite while loop in Dart?

Add a condition that eventually becomes false or execute a break statement when the required exit condition is reached. During development, an accidentally infinite command-line program can also be terminated from the terminal.

What happens when continue runs inside a Dart while loop?

Dart skips the remaining statements in the current iteration and checks the while-loop condition again. Any required counter update must occur before continue to avoid repeating the same value.

Dart While Loop Summary

In this Dart Tutorial, we learned what a while loop is, its syntax, working mechanism of while loop, nested while loop and much more with examples.

A Dart while loop checks a Boolean condition before each iteration and repeats its body while that condition is true. Keep the stopping condition and control-variable update clear, particularly when using continue or writing an intentional infinite loop.