Sub topic 1
The three core collections and their literals
This chapter introduces Dart's three core collection types and shows how to create them with literals. It covers the basic operations on each type and how to use a set for unique items.
Prerequisites
You should be comfortable with these topics before you start:
- Dart variables, functions, and control flow such as
ifandfor. - Generic type notation such as
List<int>. - Nullable types such as
int?, and the??operator that supplies a default value.
Lists: ordered, indexed sequences
A list is an ordered collection, and each element has a zero-based index. A list literal uses square brackets. Angle brackets after <> set the element type, which here is String.
void main() {
final fruits = <String>['apple', 'banana'];
fruits.add('cherry');
print(fruits[1]); // banana
print(fruits.length); // 3
}Maps: looking up values by key
A map stores key-value pairs. Keys are unique, and a lookup by key returns a nullable value, so you must handle the case where the key is missing.
void main() {
final scores = <String, int>{'ann': 90};
scores['ben'] = 85;
print(scores['cara'] ?? 0); // 0, because the key is missing
}Sets: unique elements and set operations
A set holds unique elements. Adding a duplicate does nothing, and add returns false in that case.
void main() {
final tags = <String>{'dart', 'flutter'};
print(tags.add('dart')); // false
print(tags.length); // 2
}The diagram below shows which collection fits each need.
> Note: the callout below uses the required fence format.
Exercise
Exercise
What does tags.add('dart') return when 'dart' is already in the set?
Show answer
It returns false, and the set keeps only one copy of 'dart'.