Sub topic 1
The three core collections and their literals
Dart gives you three core collection types: List, Map, and Set. Each one has a literal syntax, which is a way to write the collection directly in your source code. This chapter covers what each type is for, how to create it, how type inference treats literals, and the mistakes that trip people up. Later chapters cover reading, changing, and transforming each type in detail.
Prerequisites
This chapter assumes you already know:
- Basic Dart syntax: variables, functions, and control flow.
- Generics notation such as
List<int>andMap<String, int>. - Null safety basics, including what
int?means.
It targets Dart 3 and uses only the core library, so it needs no imports.
What each collection is for
| Type | Holds | Access by | Duplicates | Literal |
|---|---|---|---|---|
| `List<E>` | An ordered sequence of elements | Integer index (`list[0]`) | Allowed | `[1, 2, 3]` |
| `Map<K, V>` | Key-value pairs | Key (`map['a']`) | Keys are unique, values can repeat | `{'a': 1}` |
| `Set<E>` | An unordered-by-contract group of distinct elements | Membership test (`contains`) | Not allowed | `{1, 2, 3}` |
Dart's literals keep insertion order for maps and sets. The Set contract itself makes no ordering promise, though, so avoid designing around that unless a later chapter says it is safe.
List and Set both implement Iterable<E>, the interface for anything you can walk through one element at a time. Map does not implement Iterable. A map exposes keys, values, and entries, and each of those is an Iterable.
The literals
A literal creates a collection and fills it in one expression. Square brackets make a list. Curly braces with key: value pairs make a map. Curly braces with single values make a set.
void main() {
final names = ['Ada', 'Grace', 'Ada'];
final ages = {'Ada': 36, 'Grace': 45};
final tags = {'dart', 'flutter'};
print(names); // [Ada, Grace, Ada]
print(ages); // {Ada: 36, Grace: 45}
print(tags); // {dart, flutter}
print(names.length); // 3
print(ages.length); // 2
print(tags.length); // 2
}The list keeps the repeated 'Ada'. Declaring a variable final only stops you from reassigning the variable. You can still add to and remove from each collection.
You may end a literal with a trailing comma. dart format uses it to put one element per line, so most Dart code includes it in multi-line literals:
final config = {
'host': 'localhost',
'port': '8080',
};How the type is inferred
When you write a literal without a type, Dart infers the element type from the elements. It picks the most specific type that fits them all.
void main() {
final a = [1, 2, 3];
final b = [1, 2.5];
final c = [1, 'two'];
final d = <num>[1, 2];
d.add(2.5);
print(a.runtimeType); // List<int>
print(b.runtimeType); // List<num>
print(c.runtimeType); // List<Object>
print(d); // [1, 2, 2.5]
}The output above is from the Dart VM. Compiling to JavaScript can print different runtime types because JavaScript does not distinguish 1 from 1.0.
You can write the element type yourself in two ways:
- Put it before the literal:
<int>[],<String, int>{},<String>{}. - Put it on the variable:
List<int> xs = [];.
Explicit types matter in two situations. The first is when the list starts empty, because there are no elements to infer from. The second is when you want a wider type than the elements suggest. In the example above, d accepts 2.5 only because it was declared as <num>.
A mixed literal such as c is legal, but it gives you List<Object>. You then lose type checking on the elements, which is usually a sign the data needs a class or a record instead.
The empty `{}` trap
Both maps and sets use curly braces, so an empty {} is ambiguous. Dart resolves it like this:
- With no type information,
{}is aMap<dynamic, dynamic>, not a set. - With a type argument or a declared type, Dart uses that information.
void main() {
Object o = {};
final emptySet = <int>{};
Set<int> typed = {};
final emptyMap = <String, int>{};
print(o is Map); // true
print(o is Set); // false
print(emptySet is Set<int>); // true
print(typed is Set<int>); // true
print(emptyMap is Map<String, int>); // true
}The declared type Set<int> on typed supplies the context that turns {} into a set. A bare var x = {}; gets no such help, and you end up with a Map<dynamic, dynamic>. Calling x.add(1) then fails to compile. Always annotate an empty {} so the intent is clear.
A non-empty literal has no such ambiguity. {'a': 1} has colons, so it is a map. {'a', 'b'} has none, so it is a set.
Creating collections with constructors
Literals suit data you can write out by hand. Constructors suit data you compute or copy from elsewhere.
void main() {
final zeros = List<int>.filled(3, 0);
final squares = List<int>.generate(4, (i) => i * i);
final unique = Set<int>.from([1, 1, 2, 3, 3]);
final copy = List<int>.of(squares);
final byLength = Map<String, int>.fromEntries([
MapEntry('kiwi', 4),
MapEntry('plum', 4),
]);
print(zeros); // [0, 0, 0]
print(squares); // [0, 1, 4, 9]
print(unique); // {1, 2, 3}
print(copy); // [0, 1, 4, 9]
print(byLength); // {kiwi: 4, plum: 4}
}List.filled(length, value)makes a fixed-length list. You cannot add to it later. Chapter on mutability explains why.List.generate(length, builder)calls the builder once per index. The result is growable by default.Set.fromandList.fromaccept any iterable. The.ofversions require the source to already have the matching element type, so they catch type mistakes earlier.Map.fromEntriestakes an iterable ofMapEntryobjects.
Prefer literals when you can use them. Many Dart style guides recommend [] over List() and {} over Map(). The unnamed List() constructor was removed for null-safe code, so it is not available in current Dart.
Const literals
Adding const makes a compile-time constant. Every element must also be a compile-time constant.
void main() {
const primes = [2, 3, 5, 7];
const lookup = {'one': 1, 'two': 2};
const flags = {'a', 'b'};
print(identical(primes, const [2, 3, 5, 7])); // true
print(lookup['two']); // 2
print(flags.contains('a')); // true
}Dart builds identical const values only once and reuses them, which is why the identical check prints true. A const collection cannot be changed. A const set or a const map literal also rejects duplicate elements or keys at compile time.
Generics are covariant
Dart treats List<int> as a subtype of List<Object>. The assignment compiles, but unsafe writes fail at runtime instead of at compile time.
void main() {
final ints = <int>[1, 2];
final List<Object> objects = ints;
try {
objects.add('three');
} on TypeError {
print('runtime type check failed');
}
print(ints); // [1, 2]
}The underlying list is still a List<int>, so it refuses the string. Reading through the wider type is always safe. Writing through it is where the error appears. When a function only reads from a list, accept Iterable<Object> or a wide type. When it writes, ask for the exact element type.
Common errors
- Mixing up
{}for maps and sets. Annotate every empty one:<String, int>{}or<int>{}. - Mixing key-value and plain elements.
{'a': 1, 'b'}is a compile error, because Dart cannot tell whether you meant a map or a set. - Assuming
finalfreezes the contents. Useconstfor a literal whose contents never change. For a runtime collection, see the mutability chapter. - Letting a mixed literal widen to
List<Object>. Check the inferred type when the literal contains different kinds of values. - Treating a lookup like a guaranteed value.
map['missing']returnsnull, so its type isV?. The null-safety chapter covers handling it.
Exercise
Given var a = {};, var b = <int>{};, and var c = {1: 'one'};, what kind of collection is each variable, and what type would you write on a to make it an empty set of strings?
Show answer
a is a Map<dynamic, dynamic> because an untyped empty {} defaults to a map. b is an empty Set<int> because of the <int> type argument. c is a Map<int, String> because the literal contains a key-value pair. To make a an empty set of strings, write var a = <String>{}; or Set<String> a = {};.
Exercise
What static type does Dart infer for [3, 4.5, 6], and why does final xs = [1, 2]; xs.add(3.5); fail to compile?
Show answer
The first is List<num>, because num is the most specific type that covers both int and double. In the second, the literal [1, 2] contains only integers, so xs is inferred as List<int>, and a double cannot be added. Declaring final xs = <num>[1, 2]; fixes it.