0

I am trying to add a list of items to another list of item. Both list are of different types. The items are instance of 2 different classes (String , Group). Where Group contains a list of String (members) and a method to add members to the Group. here is the code...

void main(){
  void addMembersToGroups(List<String> members, List<Group> groups){
        groups.forEach((group){
            group.addMembers(members);
        });
    }
  var _members=['a','b'];
  var _groupsA=[Group()..addMembers(_members),Group()];
  var _groupsB=[Group(members:_members),Group()];

  //this function works fine
  addMembersToGroups(_members,_groupsA);

  //this function does not
  //Throws Unhandled exception:
  //Concurrent modification during iteration: Instance(length:2) of '_GrowableList'
  addMembersToGroups(_members,_groupsB);
}

and the Group class

class Group{
  List<String> members;

  Group({this.members}){members??=[];}

  void addMembers(List<String> mems) {
    members.addAll(mems);
  }
}

The problem is maybe in the _groupB variable where Group is initialized with the members field. Throws Unhandled exception: Concurrent modification during iteration: Instance(length:2) of '_GrowableList'

A bit explanation would be helpful. Thank you.

Swarup
  • 75
  • 7
  • Your problem is that what you basically are doing is adding `_members` to `_members`. In `_groupsB` you are adding `Group(members:_members)`. Since your constructor are not making a copy of the argument it will point to `_members`. Then you are calling `addMembersToGroups(_members,_groupsB)` which are calling `members.addAll(mems);` where `members` and `mems` are the same object. – julemand101 Nov 26 '20 at 12:21
  • Your constructor for `Group` should properly be: `Group({List members}) { this.members = [...?members];}`. – julemand101 Nov 26 '20 at 12:25

0 Answers0