'How to prevent changes to copied variables?

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: []}]
}


Solution 1:[1]

you can use dart:convert

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

or

b = [...a.map((e) => {...e})];

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ashtav
Solution 2 Rakesh Saini