Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter&Dart: How to remove references between parameter

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()?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading