Dart List.filled()
Syntax & Examples


Syntax of List.filled

The syntax of List.List.filled constructor is:

List.filled(int length, E fill, {bool growable = false})

This List.filled constructor of List creates a list of the given length with fill at each position.

Parameters

ParameterOptional/RequiredDescription
lengthrequiredthe length of the list to be created
fillrequiredthe value to be filled at each position in the list
growableoptional [default value is false]whether the list is allowed to grow


✐ Examples

1 Create a list of numbers filled with zeros

In this example,

  1. We create a list named numbers using List.filled with a length of 5 and filling each position with 0.
  2. We print the numbers list to standard output.

Dart Program

void main() {
  List<int> numbers = List.filled(5, 0);
  print(numbers);
}

Output

[0, 0, 0, 0, 0]

2 Create a list of characters filled with 'a'

In this example,

  1. We create a list named characters using List.filled with a length of 3 and filling each position with the character 'a'.
  2. We print the characters list to standard output.

Dart Program

void main() {
  List<String> characters = List.filled(3, 'a');
  print(characters);
}

Output

[a, a, a]

3 Create a growable list of boolean flags filled with true

In this example,

  1. We create a list named flags using List.filled with a length of 4, filling each position with true, and setting growable to true.
  2. We print the flags list to standard output.

Dart Program

void main() {
  List<bool> flags = List.filled(4, true, growable: true);
  print(flags);
}

Output

[true, true, true, true]

Summary

In this Dart tutorial, we learned about List.filled constructor of List: the syntax and few working examples with output and detailed explanation for each example.