A for (var x in xs) inside a literal generates elements without a separate loop.

Program

Play the program to build a doubled copy of a list inline.

collection_for.dart
Replay: real traced execution (multi-file project)
void main() {
  var input = [1, 2, 3];
  var doubled = [for (var n in input) n * 2];
  print(doubled);
}
  1. input ← [1, 2, 3]

    1void main() {2  var input = [1, 2, 3];3  var doubled = [for (var n in input) n * 2];
    values this step[1, 2, 3]input
  2. doubled ← [2, 4, 6]

    2var input = [1, 2, 3];3var doubled = [for (var n in input) n * 2];4print(doubled);
    values this step[2, 4, 6]doubled[1, 2, 3]input
  3. print(doubled);

    3  var doubled = [for (var n in input) n * 2];4  print(doubled);5}
    output[2, 4, 6]
    values this step[2, 4, 6]doubled
collection-for `for (var n in input) n * 2` yields each transformed element.
comprehension-like Compact alternative to `map` plus `toList`.
readable The shape of the output list matches the literal.