Skip to main content

Overview

For loops are used to execute a block of code repeatedly for a specific number of times. They are ideal when you know in advance how many iterations you need.

Basic Syntax

Basic Incrementing Loop

The most common form of a for loop increments a counter:
The loop variable can be declared with int, var, or final. Use int when you want to be explicit about the type.

Decrementing Loop

You can decrement the counter to loop backwards:

Custom Increment Values

You can modify the increment step to skip values:
Use i += n to increment by n on each iteration, or i -= n to decrement by n.

Modifying Loop Variable Inside Body

You can alter the loop variable within the loop body:
Modifying the loop variable inside the loop body can make your code harder to understand and maintain. Use custom increment values instead when possible.

Complete Example

For Loop Components

1

Initialization

Executed once before the loop starts. Typically used to declare and initialize the loop counter.
2

Condition

Checked before each iteration. The loop continues as long as this evaluates to true.
3

Increment

Executed after each iteration. Usually increments or decrements the loop counter.
4

Body

The code block that executes on each iteration.

Common Patterns

Iterating from 0 to n-1

Iterating from 1 to n

Iterating backwards

Iterating with step size

For-in Loop

Dart also provides a for-in loop for iterating over collections like lists, sets, and maps:

Best Practices

  • Use meaningful variable names instead of just i when the loop purpose isn’t obvious
  • Keep loop bodies simple and focused
  • Consider using for-in loops when iterating over collections
  • Avoid modifying the loop variable inside the loop body
  • Use break to exit early and continue to skip iterations when needed