for statement is a control flow construct used to execute a block of code repeatedly. Dart supports three primary variations: the standard C-style loop, the for-in loop for iterables, and the asynchronous await for loop for streams.
Standard for Loop
The standard for loop consists of three clauses separated by semicolons: the initializer, the condition, and the final expression (often called the increment/decrement).
Syntax
- Initialization: Executed exactly once before the loop begins. It typically declares and initializes a loop counter variable.
- Condition: A boolean expression evaluated before every iteration. If
true, the loop body executes. Iffalse, the loop terminates. - Loop Body: The block of code within the braces
{}. - Final Expression: Executed after every iteration of the loop body. It is typically used to update the loop counter.
for-in Loop
The for-in loop simplifies iteration over objects that implement the Iterable interface (such as List, Set, or Map.keys). It handles the underlying iterator mechanics automatically.
Syntax
- The
iterable_expressionis evaluated once. - An
Iteratoris obtained from the iterable. - The loop calls
moveNext()on the iterator. - If
moveNext()returnstrue, thecurrentvalue is assigned tovariable, and the body executes. - If
moveNext()returnsfalse, the loop terminates.
Asynchronous await for Loop
The await for loop is used to iterate over the events of a Stream. This construct pauses execution of the enclosing async function until the next value is available from the stream.
Syntax
- The loop waits for the stream to emit a value.
- When a value is emitted, it is assigned to
variable, and the body executes. - The loop continues until the stream sends a “done” event or the loop is explicitly broken.
Control Transfer Statements
Dart provides keywords to alter the standard flow within a loop structure.break: Immediately terminates the loop. Execution resumes at the first statement following the loop block.continue: Skips the remainder of the current iteration.- In a standard
forloop, control jumps to the final expression. - In a
for-inloop, control jumps to the next iterator check.
- In a standard
Variable Scope and Closure
Variables declared in the initialization clause of afor loop are lexically scoped to the loop body. Dart captures the value of the index for each iteration, ensuring that closures created inside the loop capture the specific value of the variable for that iteration, rather than a reference to the final value.
Master Dart with Deep Grasping Methodology!Learn More





