Dart Programming - Lists
A very commonly used collection in programming is an array. Dart represents arrays in the form of List objects. A List is simply an ordered group of objects. The dart:core library provides the List class that enables creation and manipulation of lists
Lists can be of
- Fixed Length List
- Growable List
Fixed Length List
A fixed length list’s length cannot change at runtime
Declaring a list
Syntax
var list_name = new List(initial_size)
|
The above syntax creates a list of the specified size. The list cannot grow or shrink at runtime. Any attempt to resize the list will result in an exception
Initializing a list
Syntax
lst_name[index] = value;
|
Example
void main() {
var lst = new List(3);
lst[0] = 12;
lst[1] = 13;
lst[2] = 11;
print(lst);
}
|
Output
[12, 13, 11]
|
Growable List
A growable list’s length can change at run-time
Example
void main() {
var num_list = [1,2,3];
print(num_list);
}
|
Output
[1, 2, 3]
|
The following example creates a zero-length list using the empty List() constructor. The add() function in the List class is used to dynamically add elements to the list
void main() {
var lst = new List();
lst.add(1);
lst.add(2);
print(lst);
}
|
Output
[1,2]
|
List Properties
The following table lists some commonly used properties of the List class in the dart:core library.
Sr.No | Methods & Description |
---|---|
1 | first
Returns the first element case. |
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. |