In dart, why const cities = ['Delhi', 'UP', 'Noida'];

//error is in this line

cities[0] = 'Mumbai'; is a runtime error, not a compile time error?


Solution 1: Coder2195

https://www.peachpit.com/articles/article.aspx?p=2468332&seqNum=5#:~:text=EXAMPLE%204.12&text=Unlike%20final%20variables%2C%20properties%20of,its%20values%20cannot%20be%20changed.

Use normal variables, as with constants, you cannot change the value of the list during runtime. I assume that is done with var or final, as I'm not a dart master myself.


Solution 2: croxx5f

See this answer for knowing the implications of const in dart

TLDR const variables are pre compile by dart and you cannot modify them at runtime.

const cities = ['Delhi', 'UP', 'Noida'];
  cities[0] = 'Mumbai'; // Throws at runtime

Use final or var instead.

final cities = ['Delhi', 'UP', 'Noida'];
  cities[0] = 'Mumbai'; // Works OK


Solution 3: jamesdlin

There currently is no way of indicating in Dart whether a method mutates its object or is guaranteed to leave it alone. (This is unlike, say, C++ where a method could be marked as const to indicate that it does not (visibly) mutate the object.)

Consequently, there isn't a good way for the Dart compiler to know that operator []= shouldn't be allowed to be invoked on a const object, so unfortunately it isn't known that it violates the const-ness of the object until runtime.