In Dart, Spread Operator (...) and Null-aware Spread Operator (...?) are used for inserting multiple elements in a collection like Lists, Maps, etc.
Syntaxes:
- Spread operator
...Data_structure
- Null-aware Spread operator
...?Data_structure
Example 1: Using spread operators with List.
// main function start
void main() {
// initialise a List l1
List? l1 = ["Geeks","For","Geeks"];
// initialize another List l2 using l1
List? l2=["Wow",...l1,"is","amazing"];
// print List l2
print(l2);
}
Output :
[Wow, Geeks, For, Geeks, is, amazing]
Example 2: Using Spread operator with Map.
// main function start
void main() {
// initialise a Map m1
Map? m1 = {"name":"John","age":21};
// initialize another Map m2 using m1
Map? m2={"roll no":45,"class":12,...m1};
// print Map m2
print(m2);
}
Output :
{roll no: 45, class: 12, name: John, age: 21}
Example 3: Using spread operator with Sets.
// main function start
void main() {
// first set s1
Set<int> s1 = {5, 4, 3};
// second set s2
Set<int> s2 = {3, 2, 1};
// result Set
Set<int> result = {...s1, ...s2};
// print result set
print(result);
}
Output:
{5,4,3,2,1}