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

Flutter如何实现数组对象判断:存在则删后新增、不存在直接添加逻辑

Flutter 数组对象去重添加实现方案

你可以先构造目标对象,再通过匹配条件清除原有重复项后,根据开关状态判断是否新增,修改后的代码如下:

createSwitchButtonBody(int index, bool switchValue) {
  // 提前构造目标操作对象,避免重复取值
  final targetMap = {
    "value":
        "product_attribute_${getBuilderResponseModel.data!.productAttributes![attributeValueIndex].id}",
    "key": getBuilderResponseModel
        .data!.productAttributes![attributeValueIndex].values![index].id,
  };

  // 移除数组中已存在的匹配对象,无匹配项时无副作用
  body.removeWhere((item) => 
    item['key'] == targetMap['key'] && item['value'] == targetMap['value']
  );

  // 仅开关为true时添加新对象
  if (switchValue) {
    body.add(targetMap);
  }

  print(body);
  update();
}

逻辑说明

  • 匹配规则默认同时校验key和value两个字段判断是否为重复对象,如果你业务中仅需要通过key判断重复,删除removeWhere中的value校验逻辑即可
  • 无需单独写判断是否存在的分支,removeWhere会自动处理有重复就删除、无重复就无操作的场景,代码更简洁
  • 开关为false时只会删除原有匹配对象不会新增,刚好适配开关取消选中时移除对应参数的需求

内容的提问来源于stack exchange,提问作者Siavash Mirzaei-Fard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:04