Collection Literals
List.filled and List.generate
List.filled(length, value) creates a list of length copies of the same value, useful for a uniform initial state. List.generate(length, fn) builds a list by calling fn(i) for each index i in 0..length-1, so the elements can depend on position. Both constructors return a fresh List<T> with the requested length and avoid the manual for push pattern.
Program
Play the program to build a zero-filled buffer, a counted sequence, and a list of squares without writing a loop.
list_filled_generate.dart
Replay: real traced execution (multi-file project)
void main() {
var filled = List.filled(4, 0);
var counted = List.generate(4, (i) => i + 1);
var squares = List.generate(4, (i) => i * i);
var summary = '$filled $counted $squares';
print(summary);
}
filled ← [0, 0, 0, 0]
1void main() {2 var filled = List.filled(4, 0);3 var counted = List.generate(4, (i) => i + 1);values this step[0, 0, 0, 0]filledcounted ← [1, 2, 3, 4]
2var filled = List.filled(4, 0);3var counted = List.generate(4, (i) => i + 1);4var squares = List.generate(4, (i) => i * i);values this step[1, 2, 3, 4]countedsquares ← [0, 1, 4, 9]
3var counted = List.generate(4, (i) => i + 1);4var squares = List.generate(4, (i) => i * i);5var summary = '$filled $counted $squares';values this step[0, 1, 4, 9]squaressummary ← [0, 0, 0, 0] [1, 2, 3, 4] [0, 1, 4, 9]
4var squares = List.generate(4, (i) => i * i);5var summary = '$filled $counted $squares';6print(summary);values this step[0, 0, 0, 0] [1, 2, 3, 4] [0, 1, 4, 9]summaryprint(summary);
5 var summary = '$filled $counted $squares';6 print(summary);7}output[0, 0, 0, 0] [1, 2, 3, 4] [0, 1, 4, 9]values this step[0, 0, 0, 0] [1, 2, 3, 4] [0, 1, 4, 9]summary
List.filled
`List.filled(n, v)` returns a list of `n` copies of `v`. Each slot is the same value; this is the right tool for a uniform initial state.
List.generate
`List.generate(n, fn)` calls `fn(i)` for `i = 0..n-1` and collects the results. The index lets each element vary by position without writing a `for` loop.
constructor result
Both factories return a fresh `List<T>` of the requested length, ready for downstream operations like `map`, `where`, or `join`.