Skip to main content
The while loop is a control flow statement that repeatedly executes a block of code as long as a specified boolean condition evaluates to true. It is classified as an entry-controlled loop, meaning the condition is validated prior to the execution of the loop body.

Syntax

while (condition) {
  // Statement(s) to execute
}
  • condition: An expression that must evaluate to a bool.
  • { ... }: The block of code (loop body) executed if the condition is true.

Execution Logic

  1. Evaluation: The Dart runtime evaluates the expression inside the parentheses.
  2. Branching:
    • If the condition is true, the code inside the braces executes.
    • If the condition is false, the loop terminates, and control passes to the statement immediately following the closing brace.
  3. Iteration: After the loop body executes, control returns to step 1 to re-evaluate the condition.

Code Example

The following example demonstrates a standard iteration where a counter variable controls the loop termination.
void main() {
  int count = 0;

  // The loop runs as long as count is less than 3
  while (count < 3) {
    print('Current count: $count');
    count++; // State update
  }
}
Output:
Current count: 0
Current count: 1
Current count: 2

Infinite Loops

If the condition never evaluates to false, the loop will execute indefinitely, blocking the program’s main isolate unless externally interrupted.
while (true) {
  print('This will run forever');
}

Loop Control Statements

The execution flow within a while loop can be modified using the break and continue keywords.
  • break: Immediately terminates the loop, bypassing the condition check and resuming execution after the loop body.
  • continue: Skips the remainder of the current iteration and jumps immediately to the condition evaluation for the next iteration.
int i = 0;

while (i < 5) {
  i++;

  if (i == 2) {
    continue; // Skips print for 2, jumps to condition check
  }

  if (i == 4) {
    break; // Terminates loop entirely
  }

  print(i);
}
// Output: 1, 3
Master Dart with Deep Grasping Methodology!Learn More