Collection if, for & Spread
Dart lets you put control flow inside collection literals. With if, for and the spread operator ... you can build lists, sets and maps declaratively, in one expression, instead of creating an empty collection and mutating it step by step. This style is everywhere in Flutter widget trees, but it's just as useful in plain Dart.
The spread operator ...
... inserts all elements of another collection. ...? does the same but skips null.
void main() {
var basics = ['salt', 'pepper'];
var extras = ['chili', 'lime'];
List<String>? optional;
var shopping = ['rice', ...basics, ...extras, ...?optional, 'fish sauce'];
print(shopping);
var defaults = {'theme': 'light', 'lang': 'en'};
var userPrefs = {'lang': 'vi'};
var settings = {...defaults, ...userPrefs}; // later keys win
print(settings);
var ids = {...[3, 1, 3], ...{2, 1}};
print(ids);
}[rice, salt, pepper, chili, lime, fish sauce]
{theme: light, lang: vi}
{3, 1, 2}
Spreading maps is a clean way to merge configuration: put defaults first and overrides last.
Collection if
An if inside a literal includes an element only when the condition is true. It may have an else:
List<String> menu({required bool loggedIn, required bool isAdmin}) => [
'Home',
'Shop',
if (loggedIn) 'Orders' else 'Sign in',
if (isAdmin) ...['Users', 'Reports'],
];
void main() {
print(menu(loggedIn: false, isAdmin: false));
print(menu(loggedIn: true, isAdmin: false));
print(menu(loggedIn: true, isAdmin: true));
var discount = 0;
var receipt = {
'total': 120,
if (discount > 0) 'discount': discount,
};
print(receipt);
}[Home, Shop, Sign in]
[Home, Shop, Orders]
[Home, Shop, Orders, Users, Reports]
{total: 120}
Combine if with a spread to add several elements at once, as in if (isAdmin) ...['Users', 'Reports'].
if-case in collections
Collection if also accepts a pattern with case, binding variables for the element:
void main() {
Object? nickname = 'Bi';
Object? age = 'unknown';
var labels = [
if (nickname case String n) 'nick: $n',
if (age case int a when a >= 18) 'adult',
'done',
];
print(labels);
}[nick: Bi, done]
Collection for
A for inside a literal adds one element per iteration — like an inline map:
void main() {
var prices = {'pho': 45, 'banh mi': 25, 'che': 20};
var lines = [
'MENU',
for (final MapEntry(:key, :value) in prices.entries) '${key.padRight(8)} $value',
'----',
];
print(lines.join('\n'));
var doubled = {for (final n in [1, 2, 3]) n: n * 2};
print(doubled);
var evenSquares = [
for (var i = 1; i <= 10; i++)
if (i.isEven) i * i,
];
print(evenSquares);
}MENU
pho 45
banh mi 25
che 20
----
{1: 2, 2: 4, 3: 6}
[4, 16, 36, 64, 100]
for and if nest freely — for (...) if (...) element is a filter-and-map in one line.
Imperative vs declarative
The same list built both ways:
// Imperative
final items = <String>[];
items.add('Header');
for (final p in products) {
if (p.inStock) items.add(p.name);
}
if (showFooter) items.add('Footer');
// Declarative
final items = [
'Header',
for (final p in products)
if (p.inStock) p.name,
if (showFooter) 'Footer',
];The declarative version is a single expression, so items can be final and even used directly as an argument.
| Element | Syntax | Works in |
|---|---|---|
| Spread | ...xs, ...?xs |
List, Set, Map |
| If | if (cond) x, if (cond) x else y |
List, Set, Map |
| If-case | if (v case Pattern p) x |
List, Set, Map |
| For | for (final x in xs) f(x) |
List, Set, Map |
Tip: Put a trailing comma after the last element of a multi-line literal.
dart formatthen keeps one element per line, which makes diffs cleaner.
Test yourself
What does [1, if (false) 2, 3] evaluate to?
- [1, null, 3]
- [1, 3]
- [1, 2, 3]
- Compile error
What is the difference between ...xs and ...?xs?
...?skips the spread if xs is null...?spreads in reverse...?removes duplicates- There is no difference
When merging {...a, ...b} and both maps contain the same key, which value is kept?
- The value from a
- The value from b
- Both, as a list
- It throws