Dart Collection if and for
Dart Collection if and for
A literal is a value you write directly in the code, like [1, 2, 3] or {'a': 1}.
Dart lets you write if and for inside list, set and map literals.
This is called collection if and collection for.
It lets you build a collection in one step, without calling add() many times.
Collection if
Put if before an item to add that item only when the condition is true.
Note that there are no curly brackets around the item:
Example
void main() {
var isLoggedIn = true;
var menu = ['Home', 'Tutorials', if (isLoggedIn) 'My Profile'];
print(menu);
}
Try it Yourself »
Result:
[Home, Tutorials, My Profile]
If the condition is false, the item is left out:
Example
void main() {
var isLoggedIn = false;
var menu = ['Home', 'Tutorials', if (isLoggedIn) 'My Profile'];
print(menu);
}
Try it Yourself »
Result:
[Home, Tutorials]
You can also add an else part, to pick one of two items:
Example
void main() {
var isLoggedIn = false;
var menu = ['Home', 'Tutorials', if (isLoggedIn) 'Log out' else 'Log in'];
print(menu);
}
Try it Yourself »
Result:
[Home, Tutorials, Log in]
Collection for
Put a for loop inside a literal to add one item for each run of the loop:
Example
void main() {
var numbers = [1, 2, 3, 4];
var doubled = [for (var n in numbers) n * 2];
print(doubled);
}
Try it Yourself »
Result:
[2, 4, 6, 8]
You can mix normal items and a for in the same literal:
Example
void main() {
var fruits = ['apple', 'banana'];
var shopping = ['milk', for (var f in fruits) f.toUpperCase(), 'bread'];
print(shopping);
}
Try it Yourself »
Result:
[milk, APPLE, BANANA, bread]
A classic counting loop works too:
Example
void main() {
var squares = [for (var i = 1; i <= 5; i++) i * i];
print(squares);
}
Try it Yourself »
Result:
[1, 4, 9, 16, 25]
Combine for and if
You can put an if inside a for, to keep only some items:
Example
void main() {
var scores = [45, 82, 67, 91, 38];
var passed = [for (var s in scores) if (s >= 50) s];
print(passed);
}
Try it Yourself »
Result:
[82, 67, 91]
Sets and Maps
Collection if and for also work in set literals:
Example
void main() {
var words = ['dart', 'java', 'dart', 'kotlin', 'java'];
var firstLetters = {for (var w in words) w[0]};
print(firstLetters);
}
Try it Yourself »
Result:
{d, j, k}
In a map literal, each item is a key: value pair:
Example
void main() {
var names = ['Tom', 'Anna', 'Linus'];
var nameLengths = {for (var name in names) name: name.length};
print(nameLengths);
var showEmail = true;
var user = {
'name': 'Anna',
if (showEmail) 'email': 'anna@example.com',
};
print(user);
}
Try it Yourself »
Result:
{Tom: 3, Anna: 4, Linus: 5}
{name: Anna, email: anna@example.com}