Dart Change List Items
Change an Item
To change the value of an item, assign a new value to its index:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits[1] = 'blackcurrant';
print(fruits);
}
Try it Yourself »
Result:
[apple, blackcurrant, cherry]
The list is final, but you can still change its items.
final only means that the variable always points to the same list.
Add Items
The add() method adds one item to the end of the list:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits.add('orange');
print(fruits);
}
Try it Yourself »
Result:
[apple, banana, cherry, orange]
The addAll() method adds all the items of another list to the end:
Example
void main() {
final fruits = ['apple', 'banana'];
final tropical = ['mango', 'pineapple', 'papaya'];
fruits.addAll(tropical);
print(fruits);
}
Try it Yourself »
Result:
[apple, banana, mango, pineapple, papaya]
Insert Items
The insert() method adds an item at a given index.
The items after it move one place to the right:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits.insert(1, 'orange');
print(fruits);
}
Try it Yourself »
Result:
[apple, orange, banana, cherry]
Use index 0 to add an item at the start of the list.
Remove Items
The remove() method removes the first item with the given value:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'banana'];
fruits.remove('banana');
print(fruits);
}
Try it Yourself »
Result:
[apple, cherry, banana]
remove() returns true if it found and removed the item, and false if not.
The removeAt() method removes the item at a given index, and removeLast() removes the last item.
Both methods return the item they removed:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry', 'kiwi'];
final removed = fruits.removeAt(1);
print('Removed $removed');
print(fruits);
final last = fruits.removeLast();
print('Removed $last');
print(fruits);
}
Try it Yourself »
Result:
Removed banana
[apple, cherry, kiwi]
Removed kiwi
[apple, cherry]
The removeWhere() method removes every item that matches a test.
The test is a small function that gets an item and returns true to remove it:
Example
void main() {
final scores = [45, 82, 37, 90, 61];
scores.removeWhere((score) => score < 50);
print(scores);
}
Try it Yourself »
Result:
[82, 90, 61]
The => arrow is a short way to write a function that returns one value.
You will learn more in the Dart Arrow Functions chapter.
Clear the List
The clear() method removes all items.
The list still exists, but it is empty:
Example
void main() {
final fruits = ['apple', 'banana', 'cherry'];
fruits.clear();
print(fruits);
print(fruits.length);
}
Try it Yourself »
Result:
[]
0
Note: The methods that add or remove items only work on growable lists.
On a fixed-length or const list, they throw an error (see Dart Lists).