dart中,因为在循环遍历数组的时候修改数组导致Concurrent modification during iteration 。那么如何正确的在循环遍历List时在List中插项。
时间: 2023-02-08 16:52:08 浏览: 75
Dart中,当在循环遍历数组时修改数组会导致 "Concurrent modification during iteration" 错误。为了正确地在遍历数组时插入项目,有几种方法可以使用:
1. 使用 `for` 循环和 `List.length` 来遍历数组。这样可以保证每次遍历数组的长度都是固定的,因此可以避免 "Concurrent modification during iteration" 错误。
2. 使用 `forEach` 方法遍历数组。在闭包中插入项目,可以使用 `add` 方法。
3. 使用 Iterator,使用 Iterator.moveNext() 和 Iterator.remove() 来在遍历时进行操作
示例:
```
for(int i = 0; i < list.length; i++){
if(condition){
list.insert(i, element);
i++; // 注意i需要++,避免跳过下一个元素
}
}
```
```
list.forEach((item) {
if(condition){
list.add(element);
}
});
```
```
var iterator = list.iterator;
while (iterator.moveNext()) {
var item = iterator.current;
if(condition){
iterator.remove();
list.insert(list.indexOf(item), element);
}
}
```
请注意,第三种方法可能会导致元素顺序改变。
总之,最好的方法是先将需要操作的元素复制到一个新的list中,再对这个新的list进行操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)