Dart Spread Operator
Dart Spread Operator
The spread operator is three dots: ...
It takes all the items from one collection and puts them into a new list, set or map literal.
Example
void main() {
var fruits = ['apple', 'banana'];
var food = ['bread', ...fruits, 'cheese'];
print(food);
}
Try it Yourself »
Result:
[bread, apple, banana, cheese]
Without the three dots, the whole list would be added as one item:
Example
void main() {
var fruits = ['apple', 'banana'];
var food = ['bread', fruits, 'cheese'];
print(food);
print(food.length);
}
Try it Yourself »
Result:
[bread, [apple, banana], cheese]
3
Join Lists
The spread operator is an easy way to join two or more lists into a new list:
Example
void main() {
var cars = ['Volvo', 'BMW'];
var moreCars = ['Ford', 'Mazda'];
var allCars = [...cars, ...moreCars];
print(allCars);
}
Try it Yourself »
Result:
[Volvo, BMW, Ford, Mazda]
The original lists do not change.
This also makes the spread operator a simple way to copy a list:
Example
void main() {
var original = [1, 2, 3];
var copy = [...original];
copy.add(4);
print(original);
print(copy);
}
Try it Yourself »
Result:
[1, 2, 3]
[1, 2, 3, 4]
Sets and Maps
The spread operator works in set literals too.
The new set still has no duplicates:
Example
void main() {
var tom = {'Math', 'Art'};
var anna = {'Art', 'Music'};
var subjects = {...tom, ...anna};
print(subjects);
}
Try it Yourself »
Result:
{Math, Art, Music}
In a map literal, the spread operator adds all the key and value pairs.
If the same key appears twice, only the last value is kept:
Example
void main() {
var defaults = {'theme': 'light', 'fontSize': 14};
var userSettings = {'theme': 'dark'};
var settings = {...defaults, ...userSettings};
print(settings);
}
Try it Yourself »
Result:
{theme: dark, fontSize: 14}
The Null-Aware Spread ...?
You cannot spread a value that is null.
If the collection can be null, use the null-aware spread ...? instead.
It adds the items if the collection is not null, and adds nothing if it is null:
Example
void main() {
List<String>? extras;
var pizza = ['cheese', 'tomato', ...?extras];
print(pizza);
extras = ['ham', 'olives'];
var bigPizza = ['cheese', 'tomato', ...?extras];
print(bigPizza);
}
Try it Yourself »
Result:
[cheese, tomato]
[cheese, tomato, ham, olives]
If you use ... on a nullable list, the program does not run:
Example
void main() {
List<String>? extras;
var pizza = ['cheese', 'tomato', ...extras];
print(pizza);
}
Try it Yourself »
Result:
main.dart:3:39: Error: An expression whose value can be 'null' must be null-checked before it can be dereferenced.
var pizza = ['cheese', 'tomato', ...extras];
^
Spread with if and for
You can use the spread operator together with collection if, to add many items when a condition is true:
Example
void main() {
var isAdmin = true;
var adminPages = ['Users', 'Reports'];
var menu = ['Home', 'Profile', if (isAdmin) ...adminPages];
print(menu);
}
Try it Yourself »
Result:
[Home, Profile, Users, Reports]