Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign const list variable to a non const list variable and modify it

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');

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading