【问题标题】:Assign const list variable to a non const list variable and modify it将 const 列表变量分配给非 const 列表变量并对其进行修改
【发布时间】:2021-11-10 12:41:54
【问题描述】:

我创建了一个常量列表变量,我想把它放到一个新的列表变量中并修改它的项目。但我收到一个错误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');

【问题讨论】:

    标签: dart


    【解决方案1】:

    对象的常量在对象而不是变量上。所以即使你改变了变量的类型,对象仍然会是 const。

    你的例子中有一个问题:

    List<String> newList = [];
    newList= constantList;
    

    这不是你认为的那样。它实际上做的是创建一个新的空列表,并指定newList 指向这个新列表。

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

    如果你想复制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]
    }
    
    

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

    更多关于pass-by-reference

    【讨论】:

    • 感谢 Yeasin Sheikh 添加该部分。 :)
    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2018-03-16
    • 2017-01-12
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多