Sub topic 7
Building collections with spread, collection if, and collection for
This chapter assumes you can write list, map, and set literals and read their types, such as List<int> and Map<String, int>. You should also know how null safety marks types such as int?. Here you will learn to build a collection in a single literal, without a separate loop that calls add.
Why build collections inside the literal
A common way to build a list is to create an empty one and then call add inside if statements and loops. That works, but the result is only complete after the last statement runs, and the list cannot be final and immutable-looking in one expression.
Dart lets you put control flow directly inside a collection literal. Four constructs do this:
| Construct | Syntax | What it does |
|---|---|---|
| Spread | `...other` | Inserts every element of an iterable (or every entry of a map) |
| Null-aware spread | `...?other` | Same, but inserts nothing if `other` is `null` |
| Collection if | `if (test) element` | Includes the element only when the test is true. An optional `else` supplies an alternative |
| Collection for | `for (final x in xs) element` | Includes one element for each loop iteration |
These work in list, set, and map literals. They are expressions, so the whole literal can be returned, assigned to a final, or passed as an argument. Flutter code uses them heavily in children: lists.
Spread operators
The spread operator ... takes an iterable and inserts its elements one by one. In a map literal, it takes another map and inserts its entries.
void main() {
final a = [1, 2];
final b = [...a, 3, ...a];
print(b); // [1, 2, 3, 1, 2]
final s = {...a, 2, 3};
print(s); // {1, 2, 3}, the set drops duplicates
final fromKeys = [...{'x': 1, 'y': 2}.keys];
print(fromKeys); // [x, y]
final m1 = {'a': 1, 'b': 2};
final m2 = {...m1, 'b': 20, 'c': 3};
print(m2); // {a: 1, b: 20, c: 3}
}Three details are worth noting:
- Any
Iterablecan be spread into a list or set, including another list, a set, or the result ofwhere. A map has no elements of its own, so spread itskeys,values, orentries. - In a map literal, entries are added in order and later entries replace earlier ones with the same key. In the example,
'b': 20replaces the spread value but the key keeps its original position. - In a set literal, duplicates are silently dropped, as they always are.
Null-aware spread
Spreading a nullable value without a check is a compile-time error. Add ? to skip null:
List<int> merge(List<int> base, List<int>? extra) {
return [...base, ...?extra];
}
void main() {
print(merge([1, 2], null)); // [1, 2]
print(merge([1, 2], [3])); // [1, 2, 3]
}...?extra is shorthand for "spread extra if it is not null". It does not turn a null into an empty list that you can then use elsewhere. It only affects the literal being built.
Collection if
A collection if includes an element only when its condition is true. It is not the same as the conditional operator ? :. A ternary always produces one value, whereas a collection if can produce nothing.
List<String> menu({required bool loggedIn, required bool isAdmin}) {
return [
'Home',
if (loggedIn) 'Profile' else 'Sign in',
if (loggedIn && isAdmin) ...['Users', 'Audit log'],
];
}
Map<String, Object> headers(String? token) {
return {
'Accept': 'application/json',
if (token != null) 'Authorization': 'Bearer $token',
};
}
void main() {
print(menu(loggedIn: false, isAdmin: false)); // [Home, Sign in]
print(menu(loggedIn: true, isAdmin: true));
// [Home, Profile, Users, Audit log]
print(headers(null)); // {Accept: application/json}
print(headers('abc')); // {Accept: application/json, Authorization: Bearer abc}
}Notice that:
- The
elsebranch is optional. Without it, a false test adds nothing, which is whyheaderscan leave out a key entirely rather than storingnull. - The branch can itself be a spread, as in
if (...) ...['Users', 'Audit log'], to include several elements at once. - Type promotion works inside the branch. In
headers,tokenis promoted fromString?toStringafter thetoken != nulltest, so'Bearer $token'needs no!. - In a map literal, the branch is a whole
key: valueentry.
Pattern tests with `case`
From Dart 3, the condition can be a pattern match using case. The variables the pattern declares are available in the element:
List<String> nonEmptyStrings(List<Object?> items) {
return [
for (final item in items)
if (item case String s when s.isNotEmpty) s,
];
}
void main() {
print(nonEmptyStrings(['a', 1, '', null, 'b'])); // [a, b]
}This filters and type-checks in one step. Each item that fails the pattern or the when guard is skipped.
Collection for
A collection for runs its body once per iteration and adds the resulting element each time. It accepts the same loop forms as a statement: for (final x in xs) and the classic for (var i = 0; i < n; i++).
void main() {
final words = ['kiwi', 'fig', 'banana'];
final lengths = [for (final w in words) w.length];
print(lengths); // [4, 3, 6]
final byWord = {for (final w in words) w: w.length};
print(byWord); // {kiwi: 4, fig: 3, banana: 6}
final firstLetters = {for (final w in words) w[0]};
print(firstLetters); // {k, f, b}
final cells = [
for (var r = 0; r < 2; r++)
for (var c = 0; c < 3; c++) '$r,$c',
];
print(cells); // [0,0, 0,1, 0,2, 1,0, 1,1, 1,2]
}The same loop body can use if to filter, and nesting for loops produces a flat result, not a list of lists. If you want a list of lists, wrap the inner loop in brackets: [for (...) [for (...) x]].
You can combine all four constructs in a single literal. The example below uses each of them and runs as shown:
List<int> build(List<int> base, bool showExtra, List<int>? maybe) {
return [
0,
...base,
if (showExtra) 99,
for (final n in base) n * 10,
...?maybe,
];
}
void main() {
print(build([1, 2, 3], true, null)); // [0, 1, 2, 3, 99, 10, 20, 30]
print(build([1, 2, 3], false, [7])); // [0, 1, 2, 3, 10, 20, 30, 7]
}Constants and type inference
In a const literal, spread and collection if are allowed as long as every piece is a compile-time constant. The if condition must be a constant bool, and a spread source must be a constant collection.
const debug = false;
const base = [1, 2];
const flags = ['--fast', if (debug) '--verbose', ...base];
void main() {
print(flags); // [--fast, 1, 2]
}Here flags has type List<Object>, because String and int have only Object in common. Dart infers the element type from all the elements, including spread contents. If you want a specific type, write it: <String>[...]. This also prevents a stray element of another type from silently widening the list.
Common errors and gotchas
- Spreading a nullable value.
[...maybe]fails to compile whenmaybeisList<int>?. Use...?maybe, or provide a default with...(maybe ?? const []). - Spreading a map into a list. A
Mapis not anIterable. Use...m.keys,...m.values, or...m.entries. The reverse also fails, since a list cannot be spread into a map literal. - The spread is a shallow copy. Spread copies references to the elements, not the elements themselves. Mutating a nested list through the original is visible in the copy:
void main() {
final inner = [1];
final outer = [inner];
final copy = [...outer];
inner.add(2);
print(copy); // [[1, 2]]
}- The result is a snapshot. Spreading happens when the literal is evaluated. Later changes to the source list do not change the new list. Spreading a lazy iterable such as
nums.where(...)runs it at that moment. - Duplicate keys in maps. A later spread or entry overwrites an earlier one. This is useful for "defaults, then overrides" (
{...defaults, ...overrides}) but reorder the elements and the result changes. - Confusing
ifwith? :.[cond ? 'a' : 'b']always adds one element.[if (cond) 'a']adds zero or one. Use the form that matches what you mean. - Long literals. If a literal has deeply nested
forandifelements, extract the pieces into local variables or helper functions. Readability matters more than putting everything in one expression.
Exercise
Write a function Map<String, int> scores(List<String> names, Map<String, int>? bonus). It should return a map with each name mapped to its length, then add all entries from bonus if it is not null, and leave out any name shorter than 3 characters. Use only a map literal with collection for, collection if, and a null-aware spread. What does scores(['ann', 'bo', 'cleo'], {'ann': 10}) return?
Show answer
Use { for (final n in names) if (n.length >= 3) n: n.length, ...?bonus }. The call returns {ann: 10, cleo: 4}. The name 'bo' is filtered out by the if. The entry ann: 3 is added first and then replaced by ann: 10 from the bonus map, because later entries win and the key keeps its original position.
Exercise
Why does const items = [1, if (flag) 2]; fail to compile when flag is declared as final flag = true;, and how do you fix it?
Show answer
In a const literal, the if condition must be a compile-time constant, and a final variable is only fixed at run time. Declare it as const flag = true;. Alternatively, drop const from the literal.