Spread operator, which makes it possible for us to add multiple values to a collection. This collection can be a list, a set, or a map. This operator is a replacement for add or addAll operator in dart.
The spread operator is three dots, we can use this operator to add the list values to another list and if we want to do a null-aware check we can add a question mark to the expression which you want to add to our list.
Let’s look at this simple example:
we have two simple integer lists, list1, and list2. Our first task is to add list2 to list1 and print the result. For that, I just call the list1 and use the triple dot or the spread operator after that append the list2 to list1, and at the end, I’m going to print the list and as we can see here the list2 which will start with 10 is appended to list1.
We can handle the null. Here anotherList variable which is a list and it can be null. To show anotherList can be null we are using the null safety operator and declaring it by List<int>?
Now to append an empty list anotherList to list1, Use the dot operator but before appending anotherList we write just add a question mark and this will check if the value of this variable is null if this is null it’s not going to append to the list list1 and if this is not the case the value of anotherList will be appended to list1.
In our next example, we want to see how we can use the spread operator with the object. Here we have two objects which are StudentA and StudentB, both of them are a list of Student. A Student is a class that has two parameters a name and a rollNumber. We have a named constructor. To combine these lists and add a Student with name Poly and rollNumber 15 and at the end and print all names.
For that, Let’s create a new list variable and call it as myStudents, in the assignment for myStudents, called the StudentA append the StudentB to that, and after that created a new Student with the name Ploy and rollNumber 15, and last but not least called using the for loop iterate through myStudents list to print students name.
In our next example, we have two variables which are of type map string and integer. We want to combine the maps and figure out what will happen to the map instances with the same key.
Created a new variable m3. In m3 add m1 and after that append the m2 to that.
After printing m3, we can see all of the values or the elements from the map m2 get appended to m1. Therefore we have here three elements but we can see that Apples occured just once and this is because we have a map instance with the same key which is the Apples, and the last value from Apples overwrites the other values, here, in this case, the 10 override the value of 4.
We can also add a dynamic map in m3.