Dart List.of()
Syntax & Examples
Syntax of List.of
The syntax of List.List.of constructor is:
List.of(Iterable<E> elements, {bool growable = true})This List.of constructor of List creates a list from elements.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
elements | required | the elements used to create the list |
growable | optional [default value is true] | whether the list is growable |
✐ Examples
1 Create a list from numbers
In this example,
- We create a list named
numbersby callingList.of()with elements[1, 2, 3]. - Since no
growableparameter is provided, the list is growable by default. - We print the list to standard output.
Dart Program
void main() {
List<int> numbers = List.of([1, 2, 3]);
print(numbers); // Output: [1, 2, 3]
}Output
[1, 2, 3]
2 Create a list from characters with non-growable list
In this example,
- We create a list named
charactersby callingList.of()with elements['a', 'b', 'c']and settinggrowableparameter tofalse. - As a result, the list is created with fixed size and cannot be modified after creation.
- We print the list to standard output.
Dart Program
void main() {
List<String> characters = List.of(['a', 'b', 'c'], growable: false);
print(characters); // Output: [a, b, c]
}Output
[a, b, c]
3 Create a list from strings
In this example,
- We create a list named
stringsby callingList.of()with elements['apple', 'banana', 'cherry']. - Since no
growableparameter is provided, the list is growable by default. - We print the list to standard output.
Dart Program
void main() {
List<String> strings = List.of(['apple', 'banana', 'cherry']);
print(strings); // Output: [apple, banana, cherry]
}Output
[apple, banana, cherry]
Summary
In this Dart tutorial, we learned about List.of constructor of List: the syntax and few working examples with output and detailed explanation for each example.