Dart Tutorials

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

ParameterOptional/RequiredDescription
lengthrequiredthe length of the list to be generated
generatorrequireda function that generates each element of the list based on the index
growableoptional [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,

  1. We create a list named numbers using List.generate with a length of 5.
  2. The generator function takes an index parameter and returns index + 1, effectively generating numbers from 1 to 5.
  3. 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,

  1. We create a list named characters using List.generate with a length of 3.
  2. The generator function takes an index parameter and returns the character corresponding to the ASCII value starting from 97 (which is 'a').
  3. 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,

  1. We create a list named words using List.generate with a length of 4.
  2. The generator function takes an index parameter and returns a string with the format 'Word $index'.
  3. 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.