In Dart, spread operations allow you to easily combine or create collections by spreading the elements of another collection. There are two types of spread operations: spread (...) and null-aware spread (...?).
Spread (...) Operation:
Lists:
void main() {
List<int> numbers = [1, 2, 3];
List<int> moreNumbers = [4, 5, 6];
// Combining lists using spread operation
List<int> combinedNumbers = [...numbers, ...moreNumbers];
print(combinedNumbers); // Output: [1, 2, 3, 4, 5, 6]
}
Sets:
void main() {
Set<int> setA = {1, 2, 3};
Set<int> setB = {3, 4, 5};
// Combining sets using spread operation
Set<int> combinedSet = {...setA, ...setB};
print(combinedSet); // Output: {1, 2, 3, 4, 5}
}
Maps:
void main() {
Map<String, int> mapA = {'a': 1, 'b': 2};
Map<String, int> mapB = {'b': 3, 'c': 4};
// Combining maps using spread operation
Map<String, int> combinedMap = {...mapA, ...mapB};
print(combinedMap); // Output: {a: 1, b: 3, c: 4}
}
Null-aware Spread (...?) Operation:
The null-aware spread operator (...?) is used to spread elements only if the source collection is not null.
Lists:
void main() {
List<int>? numbers = [1, 2, 3];
List<int>? moreNumbers = null;
// Combining lists using null-aware spread operation
List<int> combinedNumbers = [...?numbers, ...?moreNumbers ?? []];
print(combinedNumbers); // Output: [1, 2, 3]
}
Sets:
void main() {
Set<int>? setA = {1, 2, 3};
Set<int>? setB = null;
// Combining sets using null-aware spread operation
Set<int> combinedSet = {...?setA, ...?setB ?? <int>{}};
print(combinedSet); // Output: {1, 2, 3}
}
Maps:
void main() {
Map<String, int>? mapA = {'a': 1, 'b': 2};
Map<String, int>? mapB = null;
// Combining maps using null-aware spread operation
Map<String, int> combinedMap = {...?mapA, ...?mapB ?? <String, int>{}};
print(combinedMap); // Output: {a: 1, b: 2}
}
Spread operations are useful for creating new collections, combining existing ones, and handling cases where collections might be null. They provide a concise and readable way to manipulate collections in Dart.
ย