The syntax of List.List.generate constructor is:
List.generate(int length, E generator(int index), {bool growable = true})
This List.generate constructor of List generates a list of values.
Parameter | Optional/Required | Description |
---|---|---|
length | required | the length of the list to be generated |
generator | required | a function that generates each element of the list based on the index |
growable | optional [default value is true] | whether the list is allowed to grow |
In this example,
numbers
using List.generate
with a length of 5.generator
function takes an index
parameter and returns index + 1
, effectively generating numbers from 1 to 5.numbers
list to standard output.void main() {
List<int> numbers = List.generate(5, (index) => index + 1);
print(numbers);
}
[1, 2, 3, 4, 5]
In this example,
characters
using List.generate
with a length of 3.generator
function takes an index
parameter and returns the character corresponding to the ASCII value starting from 97 (which is 'a').characters
list to standard output.void main() {
List<String> characters = List.generate(3, (index) => String.fromCharCode(97 + index));
print(characters);
}
[a, b, c]
In this example,
words
using List.generate
with a length of 4.generator
function takes an index
parameter and returns a string with the format 'Word $index'.words
list to standard output.void main() {
List<String> words = List.generate(4, (index) => 'Word $index');
print(words);
}
[Word 0, Word 1, Word 2, Word 3]
In this Dart tutorial, we learned about List.generate constructor of List: the syntax and few working examples with output and detailed explanation for each example.