budde
budde

Reputation: 182

Concurrent modification of element children

What is the "best" method for inserting new elements after each child to a given element (element).

The following naturally gives a Concurrent modification exception

element.children.forEach((Element child){
  var new_child = new DivElement();
  element.insertBefore(new_child, child);
});

Upvotes: 4

Views: 63

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76193

The simplest way to avoid ConcurrentModificationError is to duplicate the list by calling toList() before doing modifications.

element.children.toList().forEach((Element child){
  var new_child = new DivElement();
  element.insertBefore(new_child, child);
});

Upvotes: 5

Related Questions