TExcelTAD
Home › Dart › Collection if, for & Spread

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.

dart · try it yourself
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:

dart · try it yourself
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:

dart · try it yourself
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:

dart · try it yourself
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:

dart
// 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 format then keeps one element per line, which makes diffs cleaner.

Test yourself

What does [1, if (false) 2, 3] evaluate to?

  1. [1, null, 3]
  2. [1, 3]
  3. [1, 2, 3]
  4. Compile error

What is the difference between ...xs and ...?xs?

  1. ...? skips the spread if xs is null
  2. ...? spreads in reverse
  3. ...? removes duplicates
  4. There is no difference

When merging {...a, ...b} and both maps contain the same key, which value is kept?

  1. The value from a
  2. The value from b
  3. Both, as a list
  4. It throws