Lists in Dart
The dart:core library provides the List class that enables the creation and manipulation of lists. Lists are a collection of objects, and they can be classified into two types:
- Fixed Length List
- Growable List.
Fixed Length List
A fixed-length list is a list whose length cannot be changed after initialization. The syntax for creating a fixed-length list is as follows:
Declaring a list
The syntax for declaring a fixed-length list is as given below:
List list_name = List(initial_size);
The above syntax creates a list of the specified size, and all the elements in the list are initialized to null. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception.
Initializing a list
The syntax for initializing a fixed-length list is as follows:
list_name[index] = value;
Example:
void main() {
List lst = List(3);
lst[0] = 12;
lst[1] = 13;
lst[2] = 11;
print(lst);
}
Output:
[12, 13, 11]
Growable List
A growable list is a list whose length can change at runtime. The syntax for declaring and initializing a growable list is as follows:
Declaring a List
The syntax for declaring a growable list is as given below:
List list_name = [val1, val2, val3, …];
OR
List list_name = List();
The above syntax creates a list of size zero.
Initializing a List
The syntax for initializing a growable list is as given below:
list_name[index] = value;
Example:
void main() {
List lst = [];
lst.add(12);
lst.add(13);
lst.add(11);
print(lst);
}
Output:
[12, 13, 11]
List Properties
The List class in Dart provides several properties for working with lists. Here are some of the commonly used properties:
List Properties
No | Methods & Description |
1 | first Returns the first element in the list. |
2 | isEmpty Returns true if the collection has no elements. |
3 | isNotEmpty Returns true if the collection has at least one element. |
4 | length Returns the size of the list. |
5 | last Returns the last element in the list. |
6 | reversed Returns an iterable object containing the lists values in the reverse order. |
7 | Single Checks if the list has only one element and returns it. |
Example:
void main() {
// create a list of numbers
var numbers = [1, 2, 3, 4, 5];
// access the first and last elements
print(numbers.first); // prints 1
print(numbers.last); // prints 5
// check if the list is empty or not
print(numbers.isEmpty); // prints false
print(numbers.isNotEmpty); // prints true
// get the length of the list
print(numbers.length); // prints 5
// get an iterable object containing the list's values in reverse order
var reversedNumbers = numbers.reversed;
print(reversedNumbers); // prints (5, 4, 3, 2, 1)
// check if the list has only one element and return it
print([6].single); // prints 6
}
Output:
1
5
false
true
5
(5, 4, 3, 2, 1)
6