Flutter: Collections: List
The most common collection in almost any programming language is the array. In Dart, arrays are objects of type List
. Lists allow us to store multiple values in a single variable. For example the following three variables:
final car1 = 'Toyota';
final car2 = 'Mazda';
final car3 = 'Nissan';
print(car1); // prints Toyota
print(car2); // prints Mazda
print(car3); // prints Nissan
If we use a List, it become:
final cars = ['Toyota', 'Mazda', 'Nissan'];
print(cars[0]); // prints Toyota
print(cars[1]); // prints Mazda
print(cars[2]); // prints Nissan
// Or we can print the list:
print(cars); // prints [Toyota, Mazda, Nissan]
In the previous code, we have a single variable, cars
, that stores the three strings 'Toyota', 'Mazda', and 'Nissan'
. To access the stored values, we must indicate their position (also known as index). For example, Toyota is stored in the index zero cars[0]
.
The first element in the list is always at the index 0, and the last is at the index n-1, where n is the total number of elements in the list.
In Dart, the List
is an ordered collection that maintains the insertion order of the items. If we add the elements in the following order Toyota, Mazda, Nissan the first element will be Toyota, the second one Mazda, and the third one Nissan
Create a List
There are a few ways to create lists in Dart. If you want an empty list:
// May cause a type warning. What type of element will we add?
final emptyList = [];
// Specifying the type.
final emptyList = <String>[];
// Using the List.empty() constructor
final emptyList = List<String>.empty(growable: true);
// if growable is false, we will not be able to add new elements
final emptyList = List<String>.empty(growable: false);
Note
In the past, we could use List()
to initialize an empty list, but this is now deprecated. Check more details here
Useful properties and functions
- To get the number of elements in the list:
cars.length;
- To check if the list is empty, we can check if the size equals zero,
cars.length == 0
, or we can useisEmpty
cars.isEmpty;
- To check if the list contains an element:
cars.contains('Toyota');
- To add more elements to the list:
cars.add('Ford');
- To change the value of a given index:
cars[0]="BMW";
- To delete all elements of the list:
cars.clear()
Let's run the following example in DartPad: