typestar

Loops in Dart

for-in for collections, classic for for counting, while for guards.

void main() {
  final transects = ['reeds', 'shore', 'meadow'];
  // for-in walks a collection; the classic for counts.
  for (final t in transects) {
    print('Walking the $t transect');
  }
  for (var lap = 1; lap <= 3; lap++) {
    print('Lap $lap of 3');
  }

  var batteryPct = 40;
  while (batteryPct >= 20) {
    batteryPct -= 15;
  }
  print('Camera back in the bag at $batteryPct%');
}

How it works

  1. for (final t in transects) walks the list without indexing.
  2. The classic three-part for still counts laps.
  3. while repeats until its condition goes false.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
363
Tokens
100
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 86 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →

Loops in other languages