0

i have the following

List list1 = [];
List list2 = [];

list2 = list1 ;

list1.add(1);

print(list1); // outputs [1] 
print(list2); // outputs [1] WHY?

i only change list1 .. why list2 is always be the same ..

sometimes in my app i need to make a list == another .. and this is great .. but once i make it they always be equals to each other even if i make a change to one of them

Mohammed Hamdan
  • 1,006
  • 5
  • 23

1 Answers1

2

Assign list copy with List.of constructor method:

list2 = List.of(list1);

More explanation of pointers and how it works you can find at my answer here.

lrn
  • 64,680
  • 7
  • 105
  • 121
Alex Altiox
  • 136
  • 7
  • 2
    `List.from` loses type information. [You should prefer `List.of` or `.toList`](https://dart.dev/guides/language/effective-dart/usage#dont-use-listfrom-unless-you-intend-to-change-the-type-of-the-result). – jamesdlin Jan 27 '23 at 01:18
  • @jamesdlin thanks for saving me .. can you explain more of what do you mean of losses type information ? – Mohammed Hamdan Jan 28 '23 at 10:36
  • @MohammedHamdan See [In Dart, what's the difference between List.from and .of, and between Map.from and .of?](https://stackoverflow.com/q/50320220) – jamesdlin Jan 28 '23 at 17:13