Dart Collection Literals
A list literal can build its elements from other collections and expressions inline. Spread, collection if, and collection for compute elements right inside the brackets.
Copying with spread
The spread places the three values of the first list inside a new list. Adding to the copy leaves the original at three values.
void main() {
var original = [1, 2, 3];
var copy = [...original];
copy.add(4);
print(copy);
print(original);
}Merging lists with spread
Each spread contributes its values in order. The literal also holds a plain value between the two spreads.
void main() {
var start = [1, 2];
var end = [8, 9];
var merged = [...start, 5, ...end];
print(merged);
}Null-aware spread
A nullable list is declared with the question mark after the type. The first variable holds a list, so its values spread in, and the second holds null, so its spread adds nothing.
void main() {
List<int>? maybe = [7, 8];
List<int>? missing;
print([1, ...?maybe, 2]);
print([1, ...?missing, 2]);
}Choosing elements with collection if
The flag is true, so the element 99 joins the list. A false flag would leave it out.
void main() {
var showExtra = true;
var numbers = [1, if (showExtra) 99, 2];
print(numbers);
}Building squares with collection for
The for inside the brackets visits each base number. Each visit adds one element, the square of that number.
void main() {
var bases = [1, 2, 3, 4];
var squares = [for (var n in bases) n * n];
print(squares);
}Example
void main() {
var core = [2, 4];
var bonus = true;
var board = [...core, if (bonus) 6, for (var n in core) n * 10];
print(board);
}Key points
- The spread operator ... places every element of one list inside another list.
- Spreading copies values, so the new list is separate from the source list.
- Two spreads in one literal merge two lists into one.
- The null-aware spread ...? spreads a list that may be null and adds nothing when it is null.
- A collection if includes its element only when the condition holds.
- A collection for builds one element per item it loops over.
In this example, the spread copies 2 and 4 into the new list. The collection if adds 6 because bonus is true. The collection for then adds the core values times ten, which are 20 and 40.
Try it Yourself
Edit the code, then press Run.
Running is simulated · DartPad
Exercise
What does the null-aware spread ...? do when the list it spreads holds null?