将 const 列表变量分配给非常量列表变量并修改它

uni*_*ice 1 dart

我创建了一个常量列表变量,我想将其放入一个新的列表变量并修改其项目。但我收到一个错误Unhandled Exception: Unsupported operation: Cannot remove from an unmodifiable list

const List<String> constantList = [
  'apple',
  'orange',
  'banana'
];

List<String> newList = [];
newList= constantList;
newList.remove('banana');
Run Code Online (Sandbox Code Playgroud)

jul*_*101 5

对象的常量位于对象上,而不是变量上。因此,即使更改变量的类型,该对象仍然是 const。

您的示例中存在一个问题:

List<String> newList = [];
newList= constantList;
Run Code Online (Sandbox Code Playgroud)

这并没有按照你的想法去做。它实际上所做的是创建一个新的空列表,并分配newList指向这个新列表。

然后,您将更改为newList指向 所指向的列表实例constantList。所以这段代码完成后,newList并constantList指向同一个常量列表对象。

如果您想复制 引用的列表constantList,您可以这样做:

void main() {
  const List<String> constantList = ['apple', 'orange', 'banana'];
  List<String> newList = constantList.toList();
  // Alternative: List<String> newList = [...constantList];
  newList.remove('banana');
  print(newList); // [apple, orange]
}
Run Code Online (Sandbox Code Playgroud)

另外,您可以尝试使用.addAll()

List<String> newList = [];
newList= constantList;
Run Code Online (Sandbox Code Playgroud)

该副本不是 const 列表,因此可以进行操作。

有关按引用传递的更多信息