For loops
You can iterate with the standard for
loop. For example:
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
message.write('!');
}
Closures inside of Dart’s for
loops capture the value of the index,avoiding a common pitfall found in JavaScript. For example, consider:
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
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:
candidates.forEach((candidate) => candidate.interview());
Iterable classes such as List and Set also support the for-in
form ofiteration:
var collection = [0, 1, 2];
for (var x in collection) {
print(x); // 0 1 2
}