Dart deliberately avoids the error-prone behavior of JavaScript here.
A for loop that declares its own variable will have a new version of that variable for each iteration. This goes both for for(var x = ...;;)
and for (var x in ...)
(and in the latter case, the variable can even be final).
Example showing that each iteration introduces a new independent variable:
class Box {
final Function set;
final Function get;
Box(this.get, this.set);
String toString() => "[${get()}]";
}
main() {
var boxes = [];
for (int i = 0; i < 5; i++) {
boxes.add(new Box(()=>i, (x) { i = x; }));
}
print(boxes); // [[0], [1], [2], [3], [4]]
for (int i = 0; i < 5; i++) {
boxes[i].set(i * 2 + 1);
}
print(boxes); // [[1], [3], [5], [7], [9]]
}