android – Flutter list getting sync between screens


Call toList when passing the list to navigator

This will create a new list with the same elements, which means updating the parent list won’t update the newly created one.

void main() {
  final a = [1,2,3];
  final b = a;
  
  a.add(4);
  print('a: $a');         // a: [1, 2, 3, 4]
  print('b: $b');         // b: [1, 2, 3, 4]
  
  final c = a.toList();

  a.add(5);
  print('a: $a');         // a: [1, 2, 3, 4, 5]
  print('c: $c');         // c: [1, 2, 3, 4]
}

You can also see other methods to create a new list in that manner here: How to copy list values to another list in flutter

There’s also an explanation of why that happens in an answer in that question: https://stackoverflow.com/a/58389737/10210069

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img