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

将const类型常量列表赋值给非const列表后修改报错如何解决

报错原因

你代码里的const修饰的列表属于编译期不可变常量,Dart中const初始化的集合对象没有可写的存储空间,所有增删改操作都被禁止。
你执行newList = constantList时属于引用赋值,并没有拷贝常量列表的内容,只是让newList这个变量直接指向了constantList对应的不可变列表内存地址,此时调用newList.remove()本质就是修改不可变列表,因此抛出对应错误。另外你最初初始化的空列表List<String> newList = []在赋值后会被直接丢弃,没有产生作用。

解决方法

你需要先拷贝constantList的内容生成一个新的可修改列表,再执行修改操作,有两种常用实现方式:

  • 方式1:使用List.from构造方法
const List<String> constantList = [
  'apple',
  'orange',
  'banana'
];
// 生成新的可修改列表
List<String> newList = List.from(constantList);
newList.remove('banana');
  • 方式2:使用展开运算符,写法更简洁
const List<String> constantList = [
  'apple',
  'orange',
  'banana'
];
// 展开常量列表的元素生成新列表
List<String> newList = [...constantList];
newList.remove('banana');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:06:02