typestar

Collection if and spread in Dart

Build collections declaratively, right in the literal.

void main() {
  const raining = true;
  final core = ['binoculars', 'notebook'];

  // Collection-if and spread build lists declaratively.
  final pack = [
    ...core,
    if (raining) 'lens cloth',
    for (var i = 1; i <= 2; i++) 'battery $i',
  ];
  print(pack);

  // The same forms work in maps and sets.
  final labels = {for (final item in core) item: item.length};
  print(labels);
}

How it works

  1. ...core spreads one list into another.
  2. if (raining) 'lens cloth' includes an element conditionally.
  3. for inside a literal generates elements; maps do all three too.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
362
Tokens
94
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 3 of 3 in Collections, step 12 of 27 in Language basics.

← Previous Next →