Sub topic 7
Building Collections with Spread, Collection `if`, and Collection `for`
Assume you know Dart variables, functions, generics such as List<int>, and nullable types such as List<int>?. This chapter shows how to build collections from other collections and conditions without writing repeated add calls.
Spread operators
A spread operator inserts the elements of one collection into another collection. Use ... when the source collection is known to be non-null. Use ...? when the source may be null.
List<int> buildNumbers(
List<int> base,
bool includeExtra,
List<int>? optionalNumbers,
) {
return [
0,
...base,
if (includeExtra) 99,
for (final number in base) number * 10,
...?optionalNumbers,
];
}
void main() {
print(buildNumbers([1, 2, 3], true, null));
// [0, 1, 2, 3, 99, 10, 20, 30]
print(buildNumbers([1, 2, 3], false, [7]));
// [0, 1, 2, 3, 10, 20, 30, 7]
}The spread syntax works in list, set, and map literals, but the source and destination must have compatible element types. In a map, spreading copies key-value entries:
void main() {
final defaults = <String, String>{
'theme': 'light',
'language': 'en',
};
final settings = <String, String>{
...defaults,
'theme': 'dark',
};
print(settings); // {theme: dark, language: en}
}When a later map entry has the same key, it replaces the earlier value. This makes spread useful for creating a modified copy of a map.
Collection `if`
Collection if conditionally adds elements to a literal. It is different from a statement-level if because it appears between the brackets of a list, set, or map.
List<String> menu(bool isSignedIn, bool isAdmin) {
return [
'Home',
if (isSignedIn) 'Profile',
if (isSignedIn && isAdmin) 'Admin',
if (!isSignedIn) 'Sign in',
];
}
void main() {
print(menu(true, true)); // [Home, Profile, Admin]
print(menu(false, false)); // [Home, Sign in]
}You can also use else inside a collection literal:
List<String> status(bool connected) {
return [
if (connected) 'Online' else 'Offline',
];
}For maps, both the key and value belong inside the conditional entry:
Map<String, int> scores(bool includeBonus) {
return {
'base': 10,
if (includeBonus) 'bonus': 5,
};
}Collection `for`
Collection for repeats an element expression for every item in an iterable. An iterable is a value that can provide items one at a time, such as a list or set.
void main() {
final names = ['Ada', 'Linus', 'Grace'];
final labels = [
for (final name in names) name.toUpperCase(),
];
print(labels); // [ADA, LINUS, GRACE]
}You can combine collection for with collection if:
void main() {
final numbers = [1, 2, 3, 4, 5];
final evenSquares = [
for (final number in numbers)
if (number.isEven) number * number,
];
print(evenSquares); // [4, 16]
}This style is often clearer than creating an empty list and mutating it in a loop.
Exercise
Write a function named positiveDoubles that accepts List<int> values and returns a list containing twice each positive value. For [2, -1, 4], the result should be [4, 8].
Show answer
List<int> positiveDoubles(List<int> values) => [for (final value in values) if (value > 0) value * 2];