What is the Spread Operator?
The spread operator (...) was introduced in Dart 2.3 and provides a concise way to insert multiple elements into a collection. It 'spreads' the elements of an existing collection into a new collection literal. This is especially useful when you want to combine collections, add all elements from one collection to another, or conditionally include elements.
Basic Syntax
The ...list1 expands to 1, 2, 3 inside the new list literal.
Spread with Lists
You can use the spread operator anywhere inside a list literal to insert all elements of another list.
Spread with Sets
The spread operator works similarly with sets. Note that sets maintain uniqueness, so duplicates are automatically removed.
Spread with Maps
For maps, the spread operator inserts all key‑value pairs from another map. If there are duplicate keys, later spreads override earlier ones.
Null‑Aware Spread Operator (...?)
When the collection you want to spread might be null, use the null‑aware spread operator ...?. If the expression is null, it simply contributes nothing instead of throwing an error.
Combining Spread with Collection if and for
You can mix spread operators with collection if and for to build collections dynamically.
Notice that inside the if block we used ...extraNumbers to spread the list. This is a very powerful pattern for conditional inclusion of multiple elements.
Using Spread with Function Arguments
Although the spread operator is primarily for collection literals, you can also use it to pass a list as multiple positional arguments to a function using the ... syntax inside a function call (this is a different feature called 'spread in argument lists' introduced in Dart 3.0).
This is useful when you have a list and want to pass its elements as individual arguments.
Complete Example
Key Takeaways
- The spread operator
...inserts all elements of a collection into another collection literal.
- The spread operator
- Works with Lists, Sets, and Maps.
- For maps, later spreads override keys from earlier spreads.
- Use
...?to safely spread a nullable collection – if it'snull, nothing is inserted.
- Use
- Combine with collection
ifandforfor dynamic collection building.
- Combine with collection
- Spread can also be used to pass list elements as individual function arguments (Dart 3+).