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
...corespreads one list into another.if (raining) 'lens cloth'includes an element conditionally.forinside a literal generates elements; maps do all three too.
Keywords and builtins used here
constfinalforifinvarvoid
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.
Step 3 of 3 in Collections, step 12 of 27 in Language basics.