Sub topic 14
Choosing the Right Dart Collection
Assume you know Dart variables, functions, control flow, generics such as List<int>, and nullable types such as int?. This chapter focuses on choosing between List, Map, and Set, rather than repeating every operation they support.
Start with the question you need to answer
Choose a collection based on how you will use the data:
- Use a
List<T>when position and order matter. - Use a
Map<K, V>when each value is found through a key. - Use a
Set<T>when each value should appear at most once.
| Requirement | Best first choice | Reason |
|---|---|---|
| Show tasks in their display order | `List<String>` | Items have positions |
| Find a user by an ID | `Map<String, User>` | The ID is a lookup key |
| Track selected item IDs | `Set<String>` | Duplicate selections make no sense |
| Count repeated words | `Map<String, int>` | Each word maps to a count |
| Keep a queue of pending jobs | `List<Job>` | Items are processed in sequence |
A collection's type should describe the rule your program must protect. If duplicates are invalid, a Set communicates that rule more clearly than a List plus manual duplicate checks.
Compare the trade-offs
A list gives direct index access:
final colors = ['red', 'green', 'blue'];
print(colors[1]); // greenA map gives direct key access. A missing key produces null, even when the map's value type is non-nullable:
void main() {
final prices = <String, double>{
'coffee': 3.50,
'tea': 2.75,
};
final price = prices['juice'];
print(price ?? 0.0); // 0.0
}A set provides membership operations and removes duplicates:
void main() {
final requested = ['dart', 'flutter', 'dart'];
final topics = requested.toSet();
print(topics); // {dart, flutter}
print(topics.contains('flutter')); // true
}The exact printed order of a set should not be treated as your program's main rule. Use a list when a stable sequence is part of the result.
Consider equality and ordering
Sets and map keys use equality and hashCode. For strings and numbers, the behavior is usually obvious. For custom objects, two objects with the same fields are not automatically equal. If logical duplicates must collapse, implement matching == and hashCode, or use a stable key such as an ID.
Map literals preserve insertion order in Dart's default map implementation. That does not mean every map implementation has the same ordering behavior. If sorted keys are required, choose a sorted collection such as SplayTreeMap from dart:collection.
Check mutability and nullability
Choosing a type does not decide whether the collection can change. A list may be growable, fixed-length, const, or unmodifiable. If a function should not let callers change its result, return an unmodifiable view or copy according to the API's needs.
Also distinguish a nullable collection from a collection of nullable elements:
List<int>?means the entire list may benull.List<int?>means the list exists, but an element may benull.Map<String, int?>allows missing keys and stored null values, so callers must distinguish those cases if they matter.
Exercise
You need to store unique email addresses, test whether an address is already registered, and occasionally display them alphabetically. Which collection should be the primary collection, and what extra step is needed for display?
Show answer
Use a Set<String> for uniqueness and fast membership checks. Create a list copy, then sort the copy before displaying it, so display ordering does not change the set's purpose.