Collection literals: if, for, spread and null-aware elements
suggest changeIn Dart, a list, set or map literal can contain more than a fixed list of values. It can also contain elements that decide at runtime what goes into the collection:
if (condition) elementandif (...) element else elementfor (...) element- spread:
...collectionand...?nullableCollection - null-aware elements (Dart 3.8):
?valuein lists and sets,?key: valueandkey: ?valuein maps
With these you can build a collection in one expression, where you would otherwise create an empty list and call add in a sequence of if statements. The result is usually shorter, it can be final or const, and the element type is inferred.
if, for and spread have been in the language since Dart 2.3. Null-aware elements need language version 3.8 or later (sdk: ^3.8.0 in pubspec.yaml). All examples were run with Dart 3.13.4.
For the basics of the literals see Creating a new List, Creating a new Set and Creating a new Map.
Collection if
An if element adds its element only when the condition is true. An else branch adds a different element instead, and else if chains work as in statements:
List<String> menu({required bool isAdmin, required bool isBeta}) => [
'Home',
'Profile',
if (isAdmin) 'Admin',
if (isBeta) 'Labs',
];
List<String> stylesheets(bool darkMode) => [
'base.css',
if (darkMode) 'dark.css' else 'light.css',
];
Set<String> badges(int score) => {
'member',
if (score >= 90)
'gold'
else if (score >= 70)
'silver'
else
'bronze',
};
Map<String, String> headers(bool isAdmin) => {
'Accept': 'application/json',
if (isAdmin) 'X-Admin': 'yes',
};
void main() {
print(menu(isAdmin: true, isBeta: false));
print(stylesheets(true));
print(stylesheets(false));
print(badges(72));
print(headers(true));
print(headers(false));
}
Output:
[Home, Profile, Admin]
[base.css, dark.css]
[base.css, light.css]
{member, silver}
{Accept: application/json, X-Admin: yes}
{Accept: application/json}
In a map literal the element after if is a whole key: value entry.
Compare if with a conditional expression. cond ? 'b' : null always adds an element, which may be null, so the list type becomes List<String?>. if (cond) 'b' adds nothing when the condition is false, so the list stays List<String>.
Collection for
A for element adds one element for each iteration. Both for-in and the C-style for (init; condition; update) work, and you can nest them, or put an if inside a for to filter:
void main() {
final numbers = [1, 2, 3, 4];
final squares = [for (final n in numbers) n * n];
print(squares);
final evens = [for (final n in numbers) if (n.isEven) n];
print(evens);
final grid = [
for (var row = 0; row < 2; row++)
for (var col = 0; col < 3; col++) '$row,$col',
];
print(grid);
final words = ['apple', 'banana', 'cherry'];
final lengths = {for (final w in words) w: w.length};
print(lengths);
final numbered = [for (final (i, w) in words.indexed) '${i + 1}. $w'];
print(numbered);
final firstLetters = {for (final w in [...words, 'avocado']) w[0]};
print(firstLetters);
final prices = {'apple': 1.2, 'banana': 0.5, 'cherry': 4.0};
final cheap = {
for (final MapEntry(:key, :value) in prices.entries)
if (value < 2) key: value,
};
print(cheap);
}
Output:
[1, 4, 9, 16]
[2, 4]
[0,0, 0,1, 0,2, 1,0, 1,1, 1,2]
{apple: 5, banana: 6, cherry: 6}
[1. apple, 2. banana, 3. cherry]
{a, b, c}
{apple: 1.2, banana: 0.5}
Some notes:
[for (final n in numbers) n * n]gives the same result asnumbers.map((n) => n * n).toList(), but without a closure and the extratoList(). Addingifinside covers whatwhere(...).map(...)does.- The loop variable can be a pattern:
(i, w)destructures the records fromindexed, andMapEntry(:key, :value)destructures map entries. See Destructuring. - A
forelement in a map literal gives you whatMap.fromIterabledoes, without itsdynamiccallbacks.
Spread: ... and ...?
...expression inserts every element of an Iterable (or every entry of a Map, in a map literal). ...?expression does the same, but skips the spread when the expression is null:
List<int> combine(List<int> base, List<int>? extra) => [0, ...base, ...?extra, 4];
void main() {
final base = [1, 2, 3];
print(combine(base, null));
print(combine(base, [10, 20]));
// Spread any Iterable, not only lists.
final fromSet = [...{'b', 'a'}, ...'xy'.split(''), ...Iterable.generate(3)];
print(fromSet);
// Sets remove duplicates after spreading.
final tags = {...['dart', 'flutter'], ...['dart', 'web']};
print(tags);
// Maps: later entries win.
final defaults = {'color': 'blue', 'size': 'M', 'qty': '1'};
final overrides = {'size': 'L'};
final order = {...defaults, ...overrides, 'qty': '2'};
print(order);
// A spread copies: changing the result doesn't touch the source.
final copy = [...base]..add(99);
print('$base $copy');
}
Output:
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 10, 20, 4]
[b, a, x, y, 0, 1, 2]
{dart, flutter, web}
{color: blue, size: L, qty: 2}
[1, 2, 3] [1, 2, 3, 99]
{...defaults, ...overrides} is a common way to merge maps. The spread copies only the top level (the elements themselves are shared), as described in Copying and cloning. Spreads only work inside collection literals. Dart has no spread for function arguments (see Variadic parameters and Operators).
Null-aware elements (Dart 3.8)
A common job is "add this value if it isn't null". Before Dart 3.8 you wrote if (x != null) x. Now you can put ? in front of the element:
[?x]and{?x}addxonly when it is notnull.{key: ?value}adds the entry only when the value is notnull.{?key: value}adds the entry only when the key is notnull.{?key: ?value}adds the entry only when both are non-null.
List<String> nameParts(String first, String? middle, String last) =>
[first, ?middle, last];
String? nickname(String user) => user == 'ann' ? 'annie' : null;
Map<String, String> profile(String user) => {
'user': user,
'nickname': ?nickname(user),
};
Map<String, String> routes(String? region) => {
?region: 'local',
'default': 'global',
};
Map<String, int> entry(String? k, int? v) => {?k: ?v, 'b': 2};
void main() {
final parts = nameParts('Ada', null, 'Lovelace');
print(parts);
print(parts.runtimeType);
print(nameParts('Ada', 'King', 'Lovelace'));
// Sets work the same way.
final ids = {1, ?int.tryParse('2'), ?int.tryParse('x')};
print(ids);
// Map: skip the entry when the value is null.
print(profile('bob'));
print(profile('ann'));
// Map: skip the entry when the key is null.
print(routes(null));
print(routes('eu'));
// Both: skip when either is null.
print(entry('a', null));
print(entry('a', 1));
}
Output:
[Ada, Lovelace]
List<String>
[Ada, King, Lovelace]
{1, 2}
{user: bob}
{user: ann, nickname: annie}
{default: global}
{eu: local, default: global}
{b: 2}
{a: 1, b: 2}
Notes:
- The element type is non-nullable:
partsisList<String>, notList<String?>, because?middlenever adds anull. - The expression is evaluated once.
?int.tryParse('2')callstryParseone time, whileif (int.tryParse('2') != null) int.tryParse('2')!would call it twice. ?works on any expression, including fields and getters, whichif (x != null) xcan't promote (see Null safety).- When the key of a
?key: valueentry isnull, the value expression isn't evaluated at all.
?x is for a single nullable value. ...?xs is for a nullable collection. They do different things:
| Element | null |
non-null |
|---|---|---|
?x |
nothing added | adds x as one element |
...?xs |
nothing added | adds every element of xs |
If the expression can't be null, the analyzer warns that the ? is unnecessary:
void main() {
final name = 'x';
print([?name]);
}
warning - The element can't be null, so the null-aware operator '?' is unnecessary. Try removing the operator '?'. - invalid_null_aware_operator
The warning also covers a nullable local variable that flow analysis has promoted. After String? middle; middle = 'King';, the analyzer knows middle is non-null, so [?middle] gets the same warning. That's why the examples above pass the values in as function parameters.
? drops nulls, so don't use it when null carries meaning. With JSON, {'email': ?email} leaves the key out, while {'email': email} writes "email": null. For an API those are often different things.
Patterns inside collection literals: if-case
The condition of an if element can be an if-case pattern match (Dart 3.0). Variables bound by the pattern are in scope in the element:
sealed class Shape {}
class Circle extends Shape {
final double r;
Circle(this.r);
}
class Square extends Shape {
final double side;
Square(this.side);
}
void main() {
final json = <String, Object?>{
'name': 'widget',
'tags': ['a', 'b'],
'size': {'w': 3, 'h': 4},
'price': '12.5',
};
final summary = [
if (json['name'] case String name) 'name=$name',
if (json['tags'] case [String first, ...]) 'firstTag=$first',
if (json['size'] case {'w': int w, 'h': int h}) 'area=${w * h}',
if (json['price'] case num p) 'price=$p' else 'price is not a number',
if (json['missing'] case final Object v) 'missing=$v',
];
print(summary);
final shapes = <Shape>[Circle(1), Square(2), Circle(3)];
final radii = [
for (final s in shapes)
if (s case Circle(:final r)) r,
];
print(radii);
final bigSquares = [
for (final s in shapes)
if (s case Square(side: > 1.5) && final sq) sq.side,
];
print(bigSquares);
final points = [(1, 2), (3, 4)];
print([for (final (x, y) in points) x + y]);
print({for (final (x, y) in points) x: y});
}
Output:
[name=widget, firstTag=a, area=12, price is not a number]
[1.0, 3.0]
[2.0]
[3, 7]
{1: 2, 3: 4}
for + if-case filters and casts in one step. [for (final s in shapes) if (s case Circle(:final r)) r] is a List<double>, with no whereType<Circle>() and no map. For more on patterns see Pattern matching.
Refactoring imperative code
Here is a typical function that builds command-line arguments for git log the imperative way, followed by the same logic as one literal:
class LogOptions {
final int? maxCount;
final String? author;
final bool oneLine;
final List<String> paths;
final List<String>? extraArgs;
LogOptions({
this.maxCount,
this.author,
this.oneLine = false,
this.paths = const [],
this.extraArgs,
});
}
// Before: imperative building.
List<String> gitLogArgsOld(LogOptions o) {
final args = <String>['log'];
if (o.maxCount != null) {
args.add('-n');
args.add('${o.maxCount}');
}
if (o.author != null) {
args.add('--author=${o.author}');
}
if (o.oneLine) {
args.add('--oneline');
} else {
args.add('--format=medium');
}
if (o.extraArgs != null) {
args.addAll(o.extraArgs!);
}
if (o.paths.isNotEmpty) {
args.add('--');
for (final p in o.paths) {
args.add(p.replaceAll(r'\', '/'));
}
}
return args;
}
// After: one collection literal.
List<String> gitLogArgs(LogOptions o) => [
'log',
if (o.maxCount case final n?) ...['-n', '$n'],
if (o.author case final a?) '--author=$a',
if (o.oneLine) '--oneline' else '--format=medium',
...?o.extraArgs,
if (o.paths.isNotEmpty) ...[
'--',
for (final p in o.paths) p.replaceAll(r'\', '/'),
],
];
void main() {
final cases = [
LogOptions(),
LogOptions(maxCount: 5, oneLine: true, paths: [r'lib\src', 'test']),
LogOptions(author: 'kjk', extraArgs: ['--no-merges']),
];
for (final o in cases) {
final before = gitLogArgsOld(o);
final after = gitLogArgs(o);
print(after);
assert(before.join(' ') == after.join(' '));
}
}
Output (run with dart run --enable-asserts):
[log, --format=medium]
[log, -n, 5, --oneline, --, lib/src, test]
[log, --author=kjk, --format=medium, --no-merges]
Some techniques used here:
- Several elements under one condition:
if (cond) ...[a, b]spreads a small list literal. - Binding a nullable field: public fields don't promote, so
if (o.author != null) '--author=${o.author}'wouldn't compile without a!.if (o.author case final a?)tests for null and binds a non-null localain one step.?o.authordoesn't help here, because the value is used inside a string. - Optional collections:
...?o.extraArgsreplacesif (... != null) addAll(...!).
Building a JSON map with optional fields is the other common case, and null-aware entries fit it well:
import 'dart:convert';
class User {
final String id;
final String name;
final String? email;
final DateTime? lastLogin;
final List<String> roles;
final Map<String, String>? settings;
User(this.id, this.name,
{this.email, this.lastLogin, this.roles = const [], this.settings});
// Before
Map<String, Object?> toJsonOld() {
final json = <String, Object?>{'id': id, 'name': name};
if (email != null) json['email'] = email;
if (lastLogin != null) json['lastLogin'] = lastLogin!.toIso8601String();
if (roles.isNotEmpty) json['roles'] = roles;
if (settings != null) {
settings!.forEach((k, v) => json['setting.$k'] = v);
}
return json;
}
// After
Map<String, Object?> toJson() => {
'id': id,
'name': name,
'email': ?email,
'lastLogin': ?lastLogin?.toIso8601String(),
if (roles.isNotEmpty) 'roles': roles,
for (final MapEntry(:key, :value) in settings?.entries ?? const [])
'setting.$key': value,
};
}
void main() {
final users = [
User('1', 'Ann'),
User('2', 'Bob',
email: 'bob@example.com',
lastLogin: DateTime.utc(2026, 10, 1, 9, 30),
roles: ['admin'],
settings: {'theme': 'dark'}),
];
for (final u in users) {
print(jsonEncode(u.toJson()));
assert(jsonEncode(u.toJson()) == jsonEncode(u.toJsonOld()));
}
}
Output:
{"id":"1","name":"Ann"}
{"id":"2","name":"Bob","email":"bob@example.com","lastLogin":"2026-10-01T09:30:00.000Z","roles":["admin"],"setting.theme":"dark"}
?lastLogin?.toIso8601String() combines ?. (call only if not null) with a null-aware entry (leave the key out if the result is null). For more on JSON see Object serialization.
The same style is used in Flutter widget trees, where children: [...] often contains if (loading) const Spinner(), for (final item in items) ItemTile(item) and ...extraActions.
Const collections
if, spread and null-aware elements are allowed in const literals as long as every part is a constant. for elements are not:
const debug = bool.fromEnvironment('DEBUG');
const basePlugins = ['core', 'auth'];
const String? extraPlugin = null;
const plugins = [
...basePlugins,
if (debug) 'inspector',
?extraPlugin,
];
const limits = {
'requests': 100,
if (debug) 'debugRequests': 10000,
};
void main() {
print(plugins);
print(limits);
print(identical(plugins, const ['core', 'auth']));
}
Output of dart run main.dart:
[core, auth]
{requests: 100}
true
Output of dart run -DDEBUG=true main.dart:
[core, auth, inspector]
{requests: 100, debugRequests: 10000}
false
The elements are computed at compile time. Without DEBUG, plugins is canonicalized to the same object as const ['core', 'auth'], so identical returns true.
A for element in a constant is a compile error:
const items = [1, 2, 3];
const doubled = [for (final n in items) n * 2];
error - Constant expressions don't support 'for' elements. Try replacing the 'for' element with a spread, or removing 'const'. - const_eval_for_element
Use final for such collections. See Constants for more on const.
Type inference and gotchas
void main() {
final cond = DateTime.now().year > 2000;
final mixed = [if (cond) 1 else 'one', 2];
print(mixed.runtimeType);
final empty = {};
print(empty.runtimeType);
final List<int> a = [1];
final s = {...a};
print(s.runtimeType);
final ternary = ['a', cond ? 'b' : null];
print(ternary.runtimeType);
final element = ['a', if (cond) 'b'];
print(element.runtimeType);
}
Output:
List<Object>
_Map<dynamic, dynamic>
_Set<int>
List<String?>
List<String>
- The element type is the common supertype of all the elements, including both branches of
if/else. MixingintandStringgivesList<Object>. Add a type argument (<int>[...]) when you want an error instead. {}with nothing in it is a map.{...a}is a set becauseais aList, and{...m}is a map whenmis aMap. When the spread isdynamic, Dart can't tell and reportsambiguous_set_or_map_literal_either. Write<int>{...d}or<String, int>{...d}.
Braces don't group elements. {...} after if is a set or map literal, not a block:
void main() {
final loggedIn = true;
// Braces don't group elements: this adds a Set as one element.
final oops = [if (loggedIn) {'Logout', 'Settings'}];
print(oops);
print(oops.runtimeType);
// Use a spread to add several elements under one condition.
final menu = [if (loggedIn) ...['Logout', 'Settings']];
print(menu);
// ?x drops nulls; keep them if they mean something.
final readings = <int?>[3, null, 5];
final present = [for (final r in readings) ?r];
print(present);
}
Output:
[{Logout, Settings}]
List<Set<String>>
[Logout, Settings]
[3, 5]
[for (final r in readings) ?r] does the same as readings.nonNulls.toList(). Use whichever reads better.
Also keep in mind:
- Elements are evaluated eagerly, in order, when the literal runs. There is no laziness:
[for (...) expensive(x)]callsexpensivefor every element right away. Usemapor async*generator if you want a lazyIterable(see Iterators). - You can't use statements inside a literal: no
break,continue, local variables ortry. When the logic needs those, a helper function or a plain loop is clearer. - Deep nesting of
forandifelements gets hard to read quickly. Two levels is usually the limit before it's better to extract a function.
Lints and dart fix
Several lints point out code that could use collection elements, and dart fix --apply rewrites it for you:
# analysis_options.yaml
linter:
rules:
- prefer_spread_collections
- prefer_if_elements_to_conditional_expressions
- prefer_for_elements_to_map_fromIterable
- prefer_inlined_adds
- use_null_aware_elements
Given this code:
void main(List<String> args) {
final base = [1, 2];
final verbose = args.isNotEmpty;
String? name = args.isEmpty ? null : args.first;
final a = [0]..addAll(base);
final b = ['x', verbose ? '-v' : '-q'];
final c = Map.fromIterable(base, key: (e) => e, value: (e) => e * 2);
final d = [1]..add(2);
final e = ['a', if (name != null) name];
final f = {if (name != null) 'name': name};
print([a, b, c, d, e, f]);
}
dart analyze reports:
info - bin\main.dart:6:18 - The addition of multiple elements could be inlined. Try using the spread operator ('...') to inline the addition. - prefer_spread_collections
info - bin\main.dart:7:19 - Use an 'if' element to conditionally add elements. Try using an 'if' element rather than a conditional expression. - prefer_if_elements_to_conditional_expressions
info - bin\main.dart:8:13 - Use 'for' elements when building maps from iterables. Try using a collection literal with a 'for' element. - prefer_for_elements_to_map_fromiterable
info - bin\main.dart:9:18 - The addition of a list item could be inlined. Try adding the item to the list literal directly. - prefer_inlined_adds
info - bin\main.dart:10:19 - Use the null-aware marker '?' rather than a null check via an 'if'. Try using '?'. - use_null_aware_elements
info - bin\main.dart:11:14 - Use the null-aware marker '?' rather than a null check via an 'if'. Try using '?'. - use_null_aware_elements
After dart fix --apply (and dart format) the code becomes:
final a = [0, ...base];
final b = ['x', if (verbose) '-v' else '-q'];
final c = {for (var e in base) e: e * 2};
final d = [1, 2];
final e = ['a', ?name];
final f = {'name': ?name};
use_null_aware_elements only applies when the package's SDK constraint allows Dart 3.8 or later. With an older language version, ?x is an error: "This requires the 'null-aware-elements' language feature to be enabled."
Summary
| Element | Example | Adds |
|---|---|---|
if |
if (isAdmin) 'Admin' |
the element when the condition is true |
if/else |
if (dark) 'dark.css' else 'light.css' |
one of two elements |
if-case |
if (v case int n) n |
the element when the pattern matches, with bound variables |
for |
for (final x in xs) x * 2 |
one element per iteration |
| spread | ...xs |
every element of xs (or entry of a map) |
| null-aware spread | ...?xs |
every element, or nothing if xs is null |
| null-aware element | ?x |
x, or nothing if it is null (Dart 3.8) |
| null-aware entry | 'k': ?v, ?k: v |
the entry, or nothing if the marked part is null (Dart 3.8) |
- All of them work in list, set and map literals, and they nest in any combination.
if, spread and?work inconstliterals.fordoesn't.- Use
if (...) ...[a, b]to add several elements under one condition. Braces would create a nested set or map. - Prefer
?xoverif (x != null) x. It evaluatesxonce and also works with fields that don't promote.