Sub topic 1
The Three Core Collections and Their Literals
Prerequisites
This chapter assumes that you know basic Dart syntax, variables, functions, and control flow. You should also be comfortable with static types, generics such as List<int>, and nullable types such as int?.
Collections store multiple values in one object. Dart’s three core collection types are:
List, an ordered sequence accessed by position.Map, a group of key-value pairs accessed by key.Set, an unordered group of unique values.
A collection literal creates a collection directly in source code. Dart can often infer the element types, but explicit types make the intended data clearer.
| Collection | Stores | Literal example | Typical access |
|---|---|---|---|
| `List<T>` | Ordered values | `['red', 'blue']` | `colors[0]` |
| `Map<K, V>` | Keys and values | `{'id': 42}` | `user['id']` |
| `Set<T>` | Unique values | `{'dart', 'flutter'}` | `tags.contains('dart')` |
Lists: Ordered Values
A list keeps its elements in order. Each element has an integer index, starting at zero. List literals use square brackets.
void main() {
final fruits = <String>['apple', 'banana'];
print(fruits[0]); // apple
fruits.add('cherry');
print(fruits); // [apple, banana, cherry]
}The type argument <String> says that every element should be a string. Dart can infer the same type from a non-empty literal:
final numbers = [10, 20, 30]; // List<int>Use a list when position and order matter, such as a sequence of screens, search results, or steps in a process.
Maps: Key-Value Pairs
A map associates each key with one value. Map literals use curly braces and separate each key from its value with a colon.
void main() {
final scores = <String, int>{
'Ada': 95,
'Linus': 88,
};
print(scores['Ada']); // 95
}Here, String is the key type and int is the value type. Each key can occur only once. Assigning a value to an existing key replaces its old value.
final settings = <String, bool>{
'darkMode': false,
};
settings['darkMode'] = true;
print(settings['darkMode']); // trueUse a map when a key naturally identifies a value, such as a user ID, setting name, or product code.
Sets: Unique Values
A set stores each value at most once. Set literals also use curly braces, so an explicit type is useful, especially for an empty set.
void main() {
final languages = <String>{'Dart', 'Kotlin', 'Dart'};
print(languages); // {Dart, Kotlin}
print(languages.length); // 2
}The repeated 'Dart' appears only once. Use a set when membership and uniqueness matter more than position.
An empty {} literal is commonly interpreted as an empty map. Write <String>{} when you need an empty set:
final emptyMap = <String, int>{};
final emptySet = <String>{};Exercise
Which collection should store the unique product codes scanned at a checkout, and why?
Show answer
Use a Set<String> because product codes should not be duplicated and membership checks are important.