Spread Operator ...
The spread operator ... inserts all elements of a collection into another collection literal:
var first = [1, 2, 3];
var second = [4, 5, 6];
var combined = [...first, ...second];
print(combined); // [1, 2, 3, 4, 5, 6]
// Works with sets and maps too
var setA = {1, 2, 3};
var setB = {3, 4, 5};
var merged = {...setA, ...setB};
print(merged); // {1, 2, 3, 4, 5}
var defaults = {'theme': 'light', 'lang': 'en'};
var override = {'theme': 'dark'};
var config = {...defaults, ...override};
print(config); // {theme: dark, lang: en}
Null-Aware Spread ...?
List<int>? extra = null;
var result = [1, 2, ...?extra, 3];
print(result); // [1, 2, 3] — null spread adds nothing
Collection If
Include elements conditionally inside a collection literal:
bool isAdmin = true;
var menu = [
'Home',
'Profile',
if (isAdmin) 'Admin Panel',
'Logout',
];
print(menu); // [Home, Profile, Admin Panel, Logout]
Collection For
Generate multiple elements inside a collection literal using a for loop:
var squares = [for (int i = 1; i <= 5; i++) i * i];
print(squares); // [1, 4, 9, 16, 25]
var greetings = [for (var name in ['Alice', 'Bob']) 'Hello, $name!'];
print(greetings); // [Hello, Alice!, Hello, Bob!]
Full Example
void main() {
var baseItems = ['apple', 'banana'];
var extraItems = ['cherry', 'date'];
bool includePremium = true;
var cart = [
...baseItems,
...?extraItems,
if (includePremium) 'truffle',
for (var i = 1; i <= 2; i++) 'gift_$i',
];
print(cart);
// [apple, banana, cherry, date, truffle, gift_1, gift_2]
}
Output:[apple, banana, cherry, date, truffle, gift_1, gift_2]
🧠 Quiz
1. What does the spread operator ... do?
- A) Copies a reference
- B) Inserts all elements of a collection inline ✅
- C) Converts to Set
- D) Reverses a list
2. What does ...? do differently than ...?
- A) Nothing
- B) Safely handles null collections ✅
- C) Spreads into a Set
- D) Only works with Maps
Summary
The spread operator ... merges collections inline. Use ...? for null-safe spreading. Collection if conditionally includes elements. Collection for generates multiple elements from a loop — all inside a single collection literal, without intermediate variables.