You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter迭代列表时触发Concurrent modification错误寻求解决方案

解决Flutter列表遍历并发修改异常的问题

这个问题我太熟了——你在遍历列表的同时直接修改它(比如调用add()),Dart的列表迭代器会直接抛出Concurrent modification during iteration异常,因为它不允许遍历过程中改变列表的长度。而且你的代码还有个隐藏逻辑问题:如果列表里有多个不匹配的商品,你会重复添加同一个orderItemInstance好几次,这绝对不是你想要的效果。

问题代码的核心问题点

在这段循环里,你一边遍历widget.cart.orderDetails,一边调用add()方法修改列表:

for (var item in widget.cart.orderDetails){
  if (item.productName == orderItemInstance.productName){
    // ... 更新操作
  } else {
    // 这里在遍历中修改列表,直接触发异常
    widget.cart.orderDetails.add(orderItemInstance);
    theTotal += addedAmount;
  }
}

另外还有个细节错误:productQuantity和totalPrice都是字符串类型,你直接用+=是做字符串拼接(比如"1"+"2"变成"12"),不是数值相加,这会导致数量和总价计算完全错误。

修复后的完整代码

void addProductsToCart() {
  int addedAmount = cardNum * widget.currentProduct.price;
  String note = noteTextController.text;
  int total = cardNum * widget.currentProduct.price;
  OrderItem orderItemInstance = OrderItem(
    productName: widget.currentProduct.name,
    productPrice: widget.currentProduct.price.toString(),
    productQuantity: cardNum.toString(),
    productNotes: note,
    productSupplierName: widget.supplierName,
    productImage: widget.currentProduct.image,
    totalPrice: total.toString());
  
  bool foundExistingItem = false;
  int theTotal = widget.cart.total;

  // 第一步:先遍历列表,仅处理已存在的商品更新
  for (var item in widget.cart.orderDetails) {
    if (item.productName == orderItemInstance.productName) {
      // 把字符串转成整数计算,再转回字符串
      int newQuantity = int.parse(item.productQuantity) + int.parse(orderItemInstance.productQuantity);
      item.productQuantity = newQuantity.toString();
      
      int newTotalPrice = int.parse(item.totalPrice) + int.parse(orderItemInstance.totalPrice);
      item.totalPrice = newTotalPrice.toString();
      
      theTotal += addedAmount;
      foundExistingItem = true;
      break; // 找到匹配项就跳出循环,不用继续遍历
    }
  }

  // 第二步:遍历结束后,如果没找到匹配项,再添加新商品
  if (!foundExistingItem) {
    widget.cart.orderDetails.add(orderItemInstance);
    theTotal += addedAmount;
  }

  // 更新购物车总价并刷新状态
  widget.cart.total = theTotal;
  setState(() {});
}

关键修改说明

  • 分离遍历和修改操作:先遍历完成所有检查和更新,再决定是否添加新元素,彻底避免遍历中修改列表的问题;
  • 修复数值计算错误:把字符串类型的数量和总价转成整数计算,再转回字符串,保证数值逻辑正确;
  • 添加匹配标记:用foundExistingItem变量标记是否找到已有商品,避免重复添加;
  • 优化循环效率:找到匹配项后直接break,不用遍历整个列表;
  • 修正总价赋值逻辑:原来的widget.cart.total += total会导致重复计算,现在统一用theTotal更新后赋值。

这样修改后,不仅能解决并发修改的异常,还能修复数量和总价计算的逻辑错误,同时优化了代码的可读性和效率。

内容的提问来源于stack exchange,提问作者Ahmed Wagdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:58:11