我已经创建了一个常量列表变量,我想把它放到一个新的列表变量中,并修改它的项。但是我得到了一个错误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');发布于 2021-11-10 12:49:40
对象的常量在对象上,而不是在变量上。所以即使你改变了变量的类型,对象仍然是const。
您的示例中有一个问题:
List<String> newList = [];
newList= constantList;这并不是你想的那样。它实际做的是创建一个新的空列表,并使用newList来指向这个新列表。
然后将newList更改为指向constantList所指向的list实例。所以在这段代码完成之后,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]
}此外,您还可以尝试使用.addAll()
void main(List<String> args) {
const List<String> constantList = ['apple', 'orange', 'banana'];
List<String> newList = [];
newList.addAll(constantList);
newList.remove('banana');
print(newList); //[apple, orange]
}此副本不是常量列表,因此可以进行操作。
有关pass-by-reference的更多信息
https://stackoverflow.com/questions/69913447
复制相似问题