Dart List.generate()
Syntax & Examples
Syntax of List.generate
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.
Parameters
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 |
✐ Examples
1 Generate a list of numbers from 1 to 5
In this example,
- We create a list named
numbers
usingList.generate
with a length of 5. - The
generator
function takes anindex
parameter and returnsindex + 1
, effectively generating numbers from 1 to 5. - We print the
numbers
list to standard output.
Dart Program
void main() {
List<int> numbers = List.generate(5, (index) => index + 1);
print(numbers);
}
Output
[1, 2, 3, 4, 5]
2 Generate a list of characters 'a', 'b', 'c'
In this example,
- We create a list named
characters
usingList.generate
with a length of 3. - The
generator
function takes anindex
parameter and returns the character corresponding to the ASCII value starting from 97 (which is 'a'). - We print the
characters
list to standard output.
Dart Program
void main() {
List<String> characters = List.generate(3, (index) => String.fromCharCode(97 + index));
print(characters);
}
Output
[a, b, c]
3 Generate a list of words 'Word 0', 'Word 1', 'Word 2', 'Word 3'
In this example,
- We create a list named
words
usingList.generate
with a length of 4. - The
generator
function takes anindex
parameter and returns a string with the format 'Word $index'. - We print the
words
list to standard output.
Dart Program
void main() {
List<String> words = List.generate(4, (index) => 'Word $index');
print(words);
}
Output
[Word 0, Word 1, Word 2, Word 3]
Summary
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.