Exception: Concurrent modification during iteration: Instance(length:17) of '_GrowableList'

后端 未结 3 1409
心在旅途
心在旅途 2021-01-03 22:40

I make game. In //ERROR ZONE is called Exception. I don\'t understand it. Class game has List recrangles.

void sp         


        
相关标签:
3条回答
  • 2021-01-03 23:04

    This error means that you are adding or removing objects from a collection during iteration. This is not allowed since adding or removing items will change the collection size and mess up subsequent iteration.

    The error is likely from one of these lines which you haven't posted the source for:

     s.collisionResponse(e);
     e.collision(s);
     s.collision(e);
    

    I assume one of these calls is removing an item from either the entities list or the rectangles list, during the forEach, which is not allowed. Instead you must restructure the code to remove the items outside of the list iteration, perhaps using the removeWhere method.

    Consider the following attempt to remove odd numbers from a list:

    var list = [1, 2, 3, 4, 5];
    list.forEach( (e) {
     if(e % 2 == 1) 
       list.remove(e);
    });
    

    This will fail with a concurrent modification exception since we attempt to remove the items during the list iteration.

    However, during the list iteration we can mark items for removal and then remove them in a bulk operation with removeWhere:

    var list = [1, 2, 3, 4, 5];
    var toRemove = [];
    
    list.forEach( (e) {
     if(e % 2 == 1) 
       toRemove.add(e);
    });
    
    list.removeWhere( (e) => toRemove.contains(e));
    
    0 讨论(0)
  • 2021-01-03 23:18

    try to avoid loop List too much. Using this:

    list.removeWhere((element) => element % 2 == 1;
    
    0 讨论(0)
  • 2021-01-03 23:23

    New documentation on latest Dart release 2.1.0 from https://api.dartlang.org/stable/2.1.0/dart-core/Map/removeWhere.html

    Implementation

    Map.removeWhere((key, value) => toRemove.contains(key));
    
    0 讨论(0)
提交回复
热议问题