For loops

You can iterate with the standard for loop. For example:

1. var message = StringBuffer('Dart is fun');
2. for (var i = 0; i < 5; i++) {
3. message.write('!');
4. }

Closures inside of Dart’s for loops capture the value of the index,avoiding a common pitfall found in JavaScript. For example, consider:

1. var callbacks = [];
2. for (var i = 0; i < 2; i++) {
3. callbacks.add(() => print(i));
4. }
5. callbacks.forEach((c) => c());

The output is 0 and then 1, as expected. In contrast, the examplewould print 2 and then 2 in JavaScript.

If the object that you are iterating over is an Iterable, you can use theforEach() method. Using forEach() is a good option if you don’t need toknow the current iteration counter:

1. candidates.forEach((candidate) => candidate.interview());

Iterable classes such as List and Set also support the for-in form ofiteration:

1. var collection = [0, 1, 2];
2. for (var x in collection) {
3. print(x); // 0 1 2
4. }