Create a list with values computed by a generator function.
The List.generate constructor creates a list of the given length where each element is created by calling a generator function with the element's index. This is useful for creating lists with computed or patterned values.
The generator function receives the index (from 0 to length - 1) and returns the value for that position. An optional growable parameter controls whether the resulting list supports add and remove operations.
This factory constructor is a clean alternative to using a for loop to populate a list. It's particularly useful for creating sequences, lookup tables, or initializing lists with index-dependent values.
| Name | Description | Optional |
|---|---|---|
length |
The number of elements in the list. | No |
generator |
A function that takes an index and returns the element for that position. | No |
growable |
Whether the list is growable. Defaults to true. | Yes |
var squares = List.generate(5, (i) => i * i);
print(squares); // [0, 1, 4, 9, 16]
var letters = List.generate(3, (i) => String.fromCharCode(65 + i));
print(letters); // [A, B, C]