What is a list?
A List is an ordered collection of values: a class register, a shopping cart, a playlist. Items are numbered from 0. Dart lists grow and shrink as you add and remove items.
void main() {
List<String> fruits = ['Mango', 'Apple', 'Banana'];
print(fruits);
print(fruits[0]);
print(fruits.length);
print(fruits.last);
}
[Mango, Apple, Banana]
Mango
3
Banana
List<String> says every item is a String. With var marks = [78, 92]; Dart infers List<int>. An empty list needs its type: List<int> scores = []; or var scores = <int>[];.
Adding, inserting, removing and updating
void main() {
var cart = <String>['Pen'];
cart.add('Notebook'); // at the end
cart.addAll(['Eraser', 'Scale']);
cart.insert(0, 'Bag'); // at a position
cart[1] = 'Gel pen'; // update by index
cart.remove('Eraser'); // by value
cart.removeAt(0); // by index
print(cart);
print(cart.indexOf('Scale'));
print(cart.contains('Bag'));
}
[Gel pen, Notebook, Scale]
2
false
Reading cart[10] on a short list throws a RangeError. removeLast() removes and returns the last item; clear() empties the list.
Looping over a list
void main() {
var marks = [78, 92, 65];
for (var m in marks) {
print(m);
}
for (int i = 0; i < marks.length; i++) {
print('Student ${i + 1}: ${marks[i]}');
}
}
78
92
65
Student 1: 78
Student 2: 92
Student 3: 65
Useful properties: length, first, last, isEmpty, isNotEmpty, reversed.
Sorting, reversing and searching
void main() {
var marks = [65, 92, 78, 41];
marks.sort(); // smallest first, changes the list
print(marks);
marks.sort((a, b) => b.compareTo(a)); // largest first
print(marks);
print(marks.reversed.toList());
var names = ['Rohit', 'asha', 'Meena'];
names.sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
print(names);
}
[41, 65, 78, 92]
[92, 78, 65, 41]
[41, 65, 78, 92]
[asha, Meena, Rohit]
sort changes the list itself and returns nothing, so print(marks.sort()) is an error.
map, where, reduce and fold
These methods take a function and work on every item. map and where return a lazy Iterable; add .toList() to get a list.
void main() {
var prices = [120, 450, 80, 999];
var withGst = prices.map((p) => p * 1.18).toList();
var cheap = prices.where((p) => p < 200).toList();
var total = prices.reduce((a, b) => a + b);
var count = prices.fold<int>(0, (sum, p) => sum + 1);
print(withGst.map((p) => p.toStringAsFixed(1)).toList());
print(cheap);
print(total);
print(count);
print(prices.any((p) => p > 900));
print(prices.every((p) => p > 50));
print(prices.firstWhere((p) => p > 400));
}
[141.6, 531.0, 94.4, 1178.8]
[120, 80]
1649
4
true
true
450
mapchanges each item.wherekeeps items that pass a test.reducecombines items into one value (the list must not be empty).foldis likereducebut starts from a value you give, so it also works on empty lists and can return a different type. When Dart cannot work out that type, name it:fold<int>(0, ...).anyasks "is at least one true?";everyasks "are all true?".
Spread, collection if and collection for
void main() {
var morning = ['Maths', 'Science'];
var evening = ['Art'];
bool hasPe = true;
var day = [...morning, ...evening, if (hasPe) 'PE'];
var squares = [for (var i = 1; i <= 5; i++) i * i];
var labels = [for (var s in day) s.toUpperCase()];
print(day);
print(squares);
print(labels);
}
[Maths, Science, Art, PE]
[1, 4, 9, 16, 25]
[MATHS, SCIENCE, ART, PE]
... (spread) copies all items of one list into another. Flutter uses collection if and for to build lists of widgets.
Nested lists
A list can hold lists, for example a table of marks:
void main() {
var table = [
[78, 92, 65],
[88, 71, 90],
];
print(table[1][2]);
for (var row in table) {
print(row.reduce((a, b) => a + b));
}
}
90
235
249
Fixed and unmodifiable lists
List.filled(5, 0) makes a list of five zeros. const [1, 2, 3] and List.unmodifiable(...) make lists that cannot be changed; calling add on them throws an UnsupportedError.
Common mistakes
- Using index
lengthinstead oflength - 1for the last item. - Forgetting
.toList()aftermaporwhereand then expecting aList. print(list.sort());:sortreturns nothing (void).- Calling
reduceon an empty list (it throws); usefold. - Removing items from a list while looping over it with
for-in; useremoveWhereinstead.
Key points
- A
List<T>is ordered and indexed from 0. add,insert,remove,removeAtandlist[i] = vchange a list.sortsorts in place; pass(a, b) => ...compareTo...for a custom order.map,where,reduce,fold,anyandeveryprocess all items with a function...., collectionifand collectionforbuild lists neatly.
Practice questions
1. Given [12, 7, 25, 3, 18], print the list sorted from largest to smallest.
void main() {
var n = [12, 7, 25, 3, 18];
n.sort((a, b) => b.compareTo(a));
print(n); // [25, 18, 12, 7, 3]
}2. Use where and length to count the students who scored 75 or more in [78, 64, 91, 75, 50].
void main() {
var marks = [78, 64, 91, 75, 50];
print(marks.where((m) => m >= 75).length); // 3
}3. What does [1, 2, 3].map((x) => x * 10) print without .toList()?
(10, 20, 30). It is an Iterable, which prints with round brackets.
4. Use fold to find the total price of [120, 80, 45].
void main() {
var prices = [120, 80, 45];
print(prices.fold<int>(0, (sum, p) => sum + p)); // 245
}5. Build the list [2, 4, 6, 8, 10] with a collection for.
void main() {
var evens = [for (var i = 1; i <= 5; i++) i * 2];
print(evens); // [2, 4, 6, 8, 10]
}