Home > OS >  Assign const list variable to a non const list variable and modify it
Assign const list variable to a non const list variable and modify it

Time:11-11

I have created a constant list variable and I want to put it to a new list variable and modify its items. But I get an error 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');

CodePudding user response:

The const'nes of an object is on the object and not the variable. So even if you change the type of the variable, the object is still going to be const.

One problem in your example:

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

This is not doing what you think it does. What it actually does is it creates a new empty list, and assings newList to point to this new list.

You are then changing newList to point at the list instance pointed at by constantList. So after this code is done, newList and constantList points to the same constant list object.

If you want to make a copy of the list refer to by constantList, you can do this:

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]
}

Also, you can try with .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]
}

This copy is not a const list and can therefore be manipulated.

More about pass-by-reference

  •  Tags:  
  • dart
  • Related