To create a list of size N in Dart, you can use the List.filled constructor or the List.generate constructor.
In this example,
List.filled
constructor to create a list of size N with each element initialized to a default value.List.filled
constructor takes two arguments: the size of the list and the default value for each element.void main() {
int size = 5;
int defaultValue = 0;
List<int> list = List.filled(size, defaultValue);
print('List of size \$size with default values: \$list');
}
List of size 5 with default values: [0, 0, 0, 0, 0]
In this example,
List.generate
constructor to create a list of size N with each element initialized to a specific value.List.generate
constructor takes two arguments: the size of the list and a function that returns the value for each element.void main() {
int size = 5;
int specificValue = 1;
List<int> list = List.generate(size, (index) => specificValue);
print('List of size \$size with specific values: \$list');
}
List of size 5 with specific values: [1, 1, 1, 1, 1]
In this tutorial, we learned How to create a List of size N in Dart language with well detailed examples.