Skip to main content
A while loop in Dart is a pre-test control flow statement that repeatedly executes a block of code as long as a specified boolean condition evaluates to true. Because the condition is evaluated before the loop body executes, the code block will not execute at all if the initial condition is false.

Syntax

Execution Mechanics

  1. Condition Evaluation: The loop begins by evaluating the condition expression. In Dart, this expression must evaluate strictly to a boolean (bool) type. Dart does not support implicit truthy/falsy type coercion (e.g., while (1) will result in a compile-time error).
  2. Execution: If the condition evaluates to true, the statements within the loop body are executed sequentially.
  3. Iteration: After the loop body completes, control flow returns to the top of the loop, and the condition is re-evaluated.
  4. Termination: The loop terminates immediately when the condition evaluates to false. Control flow then passes to the first statement following the loop block.

Code Example

Control Transfer Statements

You can alter the standard execution flow of a while loop using control transfer statements:
  • break: Immediately terminates the loop entirely, bypassing the condition check and transferring execution to the code following the loop block.
  • continue: Halts the current iteration, skips any remaining statements in the loop body, and immediately jumps back to re-evaluate the loop condition.

Infinite Loops

If the loop’s condition never evaluates to false—typically due to a lack of state mutation within the loop body—it results in an infinite loop. This will block the current isolate’s thread of execution indefinitely.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More