I have a global parameter template for any parameter that needs to copy these data to show in any widget. Some widgets have a function that changes the data in parameters. The issue is when the function changes the data of a parameter by using .add() or .addAll(), the global parameter data also changes. The data type that will change is List and Map.
Example:
dynamic a;
dynamic b;
a = [];
b = a;
print("List");
print("a = $a , b = $b"); //a = [] , b = []
b.addAll([1]);
print("a = $a , b = $b"); //a = [1] , b = [1]
b = [
...b,
...[2]
];
print("a = $a , b = $b"); //a = [1] , b = [1, 2]
a = {};
b = a;
print("Map");
print("a = $a , b = $b"); //a = {} , b = {}
b.addAll({'1': 1});
print("a = $a , b = $b"); //a = {1: 1} , b = {1: 1}
b = {
...b,
...{'2': 2}
};
print("a = $a , b = $b"); //a = {1: 1} , b = {1: 1, 2: 2}
How to solve this with using .add() or .addAll()?
>Solution :
Instead of assigning the same value you should assign a copy. To do that you can call toList() on it. In this example you also need to cast it to List first because you declared them as dynamic. So like
b = (a as List).toList();
For the map you can do this instead:
b = {...(a as Map)};
Edit: it seems the casting to List isn’t necessary, but the casting to Map is