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

使用Bloc操作列表报错:Unsupported operation: Cannot add to an unmodifiable list

解决Bloc列表添加/删除时的"Unmodifiable list"报错

报错原因

  • Freezed生成的状态类中,集合类型(比如List)会被自动包装成不可修改的列表(UnmodifiableListView),目的是保证状态的不可变性,防止直接修改原状态。
  • 你的代码里用了级联操作..add/..remove,这是直接在原列表上进行修改操作,而原列表是不可变的,因此触发报错。
  • 同时,Bloc的核心原则是状态不可变,每次更新都要生成新的状态对象,不能修改原状态实例里的属性。

正确的添加元素实现

创建一个包含原列表所有元素的新列表,再加入新元素,避免修改原列表:

void addInterestToMyList(
  AddMyList event,
  Emitter<InterestActionState> emit,
) {
  // 方式1:展开运算符创建新列表(简洁写法)
  emit(state.copyWith(
    selectedInterest: [...state.selectedInterest, event.selectedInterest],
  ));

  // 方式2:先复制原列表再添加(更直观)
  // final newSelectedInterests = List<String>.from(state.selectedInterest);
  // newSelectedInterests.add(event.selectedInterest);
  // emit(state.copyWith(selectedInterest: newSelectedInterests));
}

正确的删除元素实现

同样创建新列表,过滤或移除目标元素:

void removeInterestToMyList(
  RemoveFromList event,
  Emitter<InterestActionState> emit,
) {
  // 方式1:过滤掉所有匹配的元素(适合存在重复元素的场景)
  emit(state.copyWith(
    selectedInterest: state.selectedInterest.where((interest) => interest != event.selectedInterest).toList(),
  ));

  // 方式2:复制原列表后移除第一个匹配的元素
  // final newSelectedInterests = List<String>.from(state.selectedInterest);
  // newSelectedInterests.remove(event.selectedInterest);
  // emit(state.copyWith(selectedInterest: newSelectedInterests));
}

内容的提问来源于stack exchange,提问作者Gbenga B Ayannuga

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:12:25