0

I have programmed this little example so that you understand my problem. I make a copy of a list and I am eliminating values from the copy but they are also eliminated from the original. Why does this happen?

The error is: Uncaught Error: Concurrent modification during iteration: Instance of 'JSArray'.

void main() 
{
  List<String> list1 = ['jose', 'maria', 'eduardo','emiliano','paula'];
  List<String> list2 = [];
  
  
  list2 = list1;
  for(var name in list1)
  {
    String nameAux = name;
    print(nameAux);
    list2.removeLast();
  }
}

I need the original list not to remove the elements like the copy

Thanks

PabloBazan
  • 33
  • 4
  • No, you are not making a copy of your list, because `list2 = list1` just creates an additional reference to the very same list. If you want them independent, you have to clone the list. – derpirscher Oct 22 '21 at 21:59

1 Answers1

1

Few things here:

First, the following only copies the reference to the list, not the list itself

list2 = list1;

instead, you can use this

List<String> list2 = List.from(list1);

More details in this post

Then, you have another error, you cannot remove items from a list while iterating that list

  for(var name in list1)
  {
    list2.removeLast();
  }

If you really need to do that, then use this instead, but be careful when you remove an item the next items will hift:

for(var i = 0; i < this.gamesList.length; i++)
Canada2000
  • 1,688
  • 6
  • 14
  • 1
    Please don't answer to questions that have been asked and answered multiple times already, but mark it as a duplicate... Especially don't create answers referring to other posts – derpirscher Oct 22 '21 at 22:03
  • The title says otherwise, and the question also. The exception is a direct result of not cloning the list but just creating an additional reference... Because if you look at the code, op is iterating `list1` but removing from `list2` which wouldn't be a problem, if both lists were different objects and not references to the same list – derpirscher Oct 22 '21 at 22:12
  • This is the error message he listed in his question "The error is: Uncaught Error: Concurrent modification during iteration". Anyway, thanks for your comment, I will definitely use your idea with future posts. Appreciated ;0) – Canada2000 Oct 22 '21 at 22:15
  • Yes, and as I explained in the comment, this is a direct result of not cloning the list. – derpirscher Oct 22 '21 at 22:17
  • 2
    And yes, you might be new and not be able to cast closing votes yet, but that doesn't mean you should violate community rules – derpirscher Oct 22 '21 at 22:21