I usually use this method to add list into another list
List newData = data;
but one of my developer friend use this ... operator to add list into another list like this, what is the difference between this both method ? i try to search for the answer but cannot understand.
List data = [
{
'value': 'value one',
},
{
'value': 'value two',
},
];
List newData = [...data];
>Solution :
List newData = data this will create a new object to the same reference
lets assume that List data = ['a', 'b', 'c'];
so if you called
newData[0] = ‘x’;
//Lets assume the following
List data = ['a', 'b', 'c'];
List newData = data;
data[0] = 'x';
print(data);
print(newData);
//this code will print the same data for both lists, you will find in the console:
['x', 'b', 'c']
['x', 'b', 'c']
//changing the first value in the data List effected both lists
but if you created a newData = [...data]; this will create a new list and copy the data from data to newData
//Lets assume the following
List data = ['a', 'b', 'c'];
List newData = [...data];
data[0] = 'x';
print(data);
print(newData);
//this code will print the same data for both lists, you will find in the console:
['x', 'b', 'c']
['a', 'b', 'c']
//changing the first value in the data List effected only the data list
usually making a new pointer to the same reference is not what’s intended
but using the second method will take more space from the memory
UPDATE:
-
when to use the first method and when to use the second
if you want to update your list, remove, replace or add elements without saving the old data, then you can use the first method, but personally, I don’t see that you need to create anewDatalist because you can do what you want directly to yourdatalist -
If you want to update your list but saving your old data to refer to it in the future, then you must use the second method, because playing with
newDatalist does not effect the original list in that case