← Dart tutorial

Dart

Loops

Dart's for loop uses the familiar three-part structure. There's also a for-in form for stepping through every item in a list without managing an index yourself.

Example: a standard for loop

void main() {
  var total = 0;
  for (var i = 1; i <= 5; i++) {
    total += i;
  }
  print('Total: $total');
}
Total: 15

You'll meet for-in properly in the Lists lesson next — it plays the same role as Java's enhanced for-loop, C#'s foreach, and PHP's foreach: stepping through each value directly, with no manual index bookkeeping.

Example
void main() {
  var total = 0;
  for (var i = 1; i <= 5; i++) {
    total += i;
  }
  print('Total: $total');
}
Output
Total: 15