Skip to main content
The spread operator (...) inserts multiple elements from a source expression into a target collection literal. It evaluates an expression yielding an Iterable or Map and expands its individual elements or key-value pairs into the surrounding context.

Syntax and Placement

The operator is placed immediately preceding an expression that evaluates to a collection. This expression is not limited to variable identifiers; it can be a function call, a direct collection literal, or any other logic that results in a compatible collection object.

List and Set Expansion

When used within a List or Set literal, the operator iterates through the resulting Iterable of the expression and appends each element to the target collection.
List<int> getNumbers() => [1, 2];

// Spreading a function result (expression)
var target = [0, ...getNumbers(), 3]; 
// Result: [0, 1, 2, 3]

Map Expansion

When used within a Map literal, the operator expands the resulting Map expression, inserting its key-value pairs into the target map.
var source = {'a': 1};

// Spreading a variable and a literal expression
var target = {'x': 0, ...source, ...{'b': 2}}; 
// Result: {'x': 0, 'a': 1, 'b': 2}

Null-Aware Spread Operator (...?)

The null-aware spread operator (...?) handles scenarios where the source expression evaluates to null. If the expression is null, the operator bypasses the expansion and inserts nothing, preventing a runtime exception.
List<int>? nullableList; // Currently null
var target = [1, ...?nullableList, 2];
// Result: [1, 2]

Type Constraints

The spread operator enforces static type safety. The element type of the source expression must be assignable to the element type of the destination collection.
  • Lists/Sets: If spreading into a List<T>, the source expression must evaluate to an Iterable<S> where S is a subtype of T.
  • Maps: If spreading into a Map<K, V>, the source expression must evaluate to a Map<K2, V2> where K2 is a subtype of K and V2 is a subtype of V.

Evaluation Order

Spread elements are evaluated in the order they appear in the literal (left-to-right). If a map spread contains keys that already exist in the target map, the later entries overwrite the earlier ones.
var first = {'key': 'initial'};
var second = {'key': 'overwritten'};
var combined = {...first, ...second};
// Result: {'key': 'overwritten'}
Master Dart with Deep Grasping Methodology!Learn More