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

Flutter freezed修改Map报错Cannot modify unmodifiable map

问题根因

你遇到的Unsupported operation: Cannot modify unmodifiable map错误来自Freezed框架的默认特性:

  • Freezed生成的实体类默认是完全不可变的,所有通过@Default初始化的集合(List/Map),都会被自动包装为不可修改的集合
  • 你在copyWithSelected方法中直接对原实体的mySelected执行键值赋值、对selectedVariants执行add操作,本质是在修改不可变对象,直接触发运行时异常
  • 你当前方法最后手动构造AdditionEntity时仅传了additionModel字段,其余字段都会重置为默认值,就算不报错之前的修改也不会生效
修复步骤
  • 所有集合修改操作,都要先基于原集合创建可修改的副本,不要直接操作原实体上的不可变集合
  • 不要手动构造新的实体实例,使用Freezed自动生成的copyWith方法传参,避免漏传字段导致其他状态丢失
  • 补全循环终止条件,避免未匹配到目标变体时出现死循环
修复后代码参考
part 'addition_entity.freezed.dart';

@freezed
class AdditionEntity with _$AdditionEntity {
  const AdditionEntity._();

  const factory AdditionEntity({
    required AdditionModel additionModel,
    @Default([])   List<Map<String,String>> selectedVariants,
    @Default({})   Map<String,String> mySelected,
    @Default(false) final bool progress,
    @Default(true) final bool enabled,
  }) = _AdditionEntity;

  AdditionEntity copyWithSelected(AdditionVariantModel selectedAdditionVariant){
    bool selected = false;
    var currentLevel = 0;
    // 创建原集合的可修改副本
    final updatedSelected = Map<String, String>.from(mySelected);
    final updatedVariants = List<Map<String, String>>.from(selectedVariants);

    while(!selected){
      if(currentLevel == 0) {
        if(additionModel.variants!.contains(selectedAdditionVariant)){
            updatedSelected['additionid'] = additionModel.id!;
            // 原代码键名存在拼写错误,已修正,可根据实际接口要求调整
            updatedSelected['additionVariantId'] = selectedAdditionVariant.id!;
            updatedSelected['level']= currentLevel.toString();
            updatedVariants.add(updatedSelected);
            selected = true;
        }
      } else {
        // 待补全多层级变体匹配逻辑
      }
      currentLevel++;
      // 新增循环终止条件,避免死循环,最大层级可根据业务调整
      if(currentLevel > 10) break;
    }
    // 使用copyWith返回新的不可变实例,保留原有其他字段状态
    return copyWith(
      additionModel: selectedAdditionVariant.addition!,
      selectedVariants: updatedVariants,
      mySelected: updatedSelected,
    );
  }
}

注意:原代码中aditionVariontid属于拼写错误,传参给接口前建议核对字段名,避免参数不匹配的问题。

内容的提问来源于stack exchange,提问作者Andrii Havryliak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 20:01:19