0

I have two variables, A and B with Map data type, when A is copied with B then I make changes in A, but B also changes. The expected result only A changed, how to solve it? Thank you

List a = [{"id": 1, "data": []}], b = [];

void main() {
  b = List.from(a);
  
  a[0]['data'].add(123);

  // result
  print(a); // [{id: 1, data: [123]}]
  print(b); // [{id: 1, data: [123]}]

  // expected results
  // print(a); // [{id: 1, data: [123]}]
  // print(b); // [{id: 1, data: []}]
}
Ashta V
  • 43
  • 1
  • 6
  • Your expected results should not be expected. What you currently get is expected with the code you have. You are making a copy of the list object, but the contents of the list are still the same object. You would need to do a deep copy which is not natively implemented. You'll need to manually write a method of doing a deep copy. – Christopher Moore Apr 29 '22 at 04:00
  • Try once to initialize the List a and b inside the main function. – Rakesh Saini Apr 29 '22 at 04:01
  • @RakeshSaini What will that change. They are still not copying the internal objects in the list. This behavior is expected regardless of where the initialization is done. – Christopher Moore Apr 29 '22 at 04:08
  • Does this answer your question? [How can I clone an Object (deep copy) in Dart?](https://stackoverflow.com/questions/13107906/how-can-i-clone-an-object-deep-copy-in-dart) – Nathan Mills Apr 29 '22 at 04:25

2 Answers2

1

you can use dart:convert

b = json.decode(json.encode(a));

or

b = [...a.map((e) => {...e})];
Ashtav
  • 2,586
  • 7
  • 28
  • 44
0

In my case its working fine you can check in the screenshot attached. I created a simple array.

  var arr = ['a','b','c','d','e'], b=[]; 
  void main() {
    b = List.from(arr);
    arr[0] = "100";
    for (int i = 0; i < arr.length; i++) {
      print('hello ${arr[i]}');
       print('hello ${b[i]}');
    }
  }

Output -

hello 100
hello a
hello b
hello b
hello c
hello c
hello d
hello d
hello e
hello e

enter image description here

Rakesh Saini
  • 660
  • 2
  • 7
  • 20
  • Thanks for your answer, it's work. But, what if var arr = [{'a': 1}] ? then we set arr[0]['a'] = 2; variable b follows variable arr. – Ashta V Apr 29 '22 at 05:40