Home > database >  Changing var 1 value also effect var2(assigned to var1)
Changing var 1 value also effect var2(assigned to var1)

Time:09-09

I have one var with some string values assigning this to other var.

var stringList1=[
  'value1',
  'value2',
  'value3',
  'value4',
];
var stringList2=stringList1;
 stringList2.remove("value3");

Problem: Deleting some value from stringList2 also deletes the value from stringList1. What I am making wrong here. I need to assign the first var value to others but the first should remain unchangeable so I can use it somewhere else in the code.

CodePudding user response:

When you create a new List variable from another one, the new one points to the reference of the first. It means that they are kind of "linked" and any changes in one of them are going to be listened by the other one, since they both have the same reference in memory. @eamirho3ein gave you a way to avoid this behavior, but I consider this is a better approach:

final stringList2=List<String>.from(stringList1);

And that's it! Is copies the values in one list and created a new reference for the new variable.

CodePudding user response:

What you are doing is passing variable by reference, in this case if you change fist one, the second one would change too, you should pass variable by value ,Try this:

 var stringList1=[
      'value1',
      'value2',
      'value3',
      'value4',
    ];
    var stringList2 =[];
    stringList2.addAll(stringList1);
    stringList2.remove("value3");
    print("stringList1 = $stringList1"); // stringList1 = [value1, value2, value3, value4]
    print("stringList2 = $stringList2"); // stringList2 = [value1, value2, value4]

see more information

CodePudding user response:

try this 
 var stringList1=[
  'value1',
  'value2',
  'value3',
  'value4',
];

setState((){
stringList2 = stringList1.remove("value3");
});
   
  • Related