0

I have an error: "ConcurrentModificationError" - Breaking on exception: Concurrent modification during iteration: Instance of 'ObservableList'.

When I want delete some items by ObservableList during "ForEach" used to "search" items.

Code Example:

.html

<template repeat="{{f in SelectedFiles}}">
    <li>
        <span class="label">{{f.name}}"">

        <button class="tiny" on-click="{{deleteDataSetFile}}" data-file="{{f.path}}">Delete</button>
    </li>
</template>

.dart

@observable List<String> fileSelected;

void deleteDataSetFile(Event event, var detail, var target) {

    String datafile = target.attributes['data-file'];

    for(var file in this.SelectedFiles){
        if(file.path==datafile){
        this.SelectedFiles.remove(file);
        }
    }
}
Domenico Monaco
  • 1,236
  • 12
  • 21

2 Answers2

2

This doesn't work in most programming languages.

Workarounds:

iterate over a copy of the list

@observable List<String> fileSelected;

void deleteDataSetFile(Event event, var detail, var target) {
  String datafile = target.attributes['data-file'];
  for(var file in this.SelectedFiles.toList()){ // added .toList() which returns a copy
    if(file.path==datafile){
      this.SelectedFiles.remove(file);
    }
  }
}

store the elements and remove them later

@observable List<String> fileSelected;

void deleteDataSetFile(Event event, var detail, var target) {
  String datafile = target.attributes['data-file'];
  List<String> itemsToRemove = [];
  for(var file in this.SelectedFiles){ 
    if(file.path==datafile){
      itemsToRemove.add(file);
    }
  }
  for(var file in itemsToRemove) {
    this.SelectedFiles.remove(file);
  }
}

if you iterate differently you can delete while iterating

  for(int i = 0; i < this.SelectedFiles.length;){ 
    if(file.path==datafile){
      this.SelectedFiles.removeAt(i)
    } else {
      i++;
    }
  }

or use the retainWhere/removeWhere method of List

this.SelectedFiles.retainWhere((e) => e.path != dataFile);
this.SelectedFiles.removeWhere((e) => e.path == dataFile);
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

SOLUTION in ".dart"

@observable List<String> fileSelected;

void deleteDataSetFile(Event event, var detail, var target) {

    String datafile = target.attributes['data-file']; 
    var tmp;
    for(var file in this.SelectedFiles){
        if(file.path==datafile){
           tmp = file;
        }
    }
    if(tmp!=null){
        this.SelectedFiles.remove(tmp);
    }
}
Domenico Monaco
  • 1,236
  • 12
  • 21