What are spread operators vs null-aware spread operators in Dart?

In Dart, the spread operator and the null-aware spread operator are used to combine or merge Map objects.

However, these operators have a crucial difference. The null-aware spread operator is used to prevent a program from throwing an error when any of the Map objects to be combined are null.

Spread operator

The spread operator is denoted by three dots ... followed by the Map object’s name, as shown below:

...(Map_name),...(Map_name2);

Code

The following code shows how to use the spread operator method in Dart.

void main() {
Map map1 = {'name':'Maria','Id':'193HQ031'};
Map map2 = {'dept':'Computer Science','level':'400'};
Map map3 = {1: 'one', 2: 'two'};
// spread operator merges maps
var mergeMap = {...map1, ...map2, ...map3};
print(mergeMap);
}

Null-aware spread operator

The null-aware spread operator is denoted by three dots with a question mark, i.e., ...?. This operator automatically checks for null objects.

The syntax of the null-aware spread operator is shown below:

...?(Map_name), ...?(Map_name2);

Suppose we have three Map objects and one of the objects is null:

Map map1 = {1: 'Mango', 2: 'Apple'};
Map map2 = {3: 'Orange', 4: 'Watermelon'};
Map map3 = null;

If we try to combine these Map objects using the spread operator, the program will throw an exception:

NoSuchMethodError: The getter 'entries' was called on null.

To solve this problem, we use the null-aware spread operator (...?), as it deals with null objects.

Code

The following code shows how to use the null-aware spread operator method in Dart.

void main() {
Map map1 = {1: 'Mango', 2: 'Apple'};
Map map2 = {3: 'Orange', 4: 'Watermelon'};
Map map3 = null;
// null-aware spread operator merges maps
var mergeMap = {...?map1, ...?map2, ...?map3};
print(mergeMap);
}