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
Parameter | Optional/Required | Description |
---|---|---|
length | required | the length of the list to be created |
fill | required | the value to be filled at each position in the list |
growable | optional [default value is false] | whether the list is allowed to grow |
✐ Examples
1 Create a list of numbers filled with zeros
In this example,
- We create a list named
numbers
usingList.filled
with a length of 5 and filling each position with 0. - 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,
- We create a list named
characters
usingList.filled
with a length of 3 and filling each position with the character 'a'. - 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,
- We create a list named
flags
usingList.filled
with a length of 4, filling each position withtrue
, and settinggrowable
totrue
. - 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.