In dart, why
const cities = ['Delhi', 'UP', 'Noida'];
//error is in this line
cities = 'Mumbai';
is a runtime error, not a compile time error?
Solution 1: Coder2195
Use normal variables, as with constants, you cannot change the value of the list during runtime.
I assume that is done with
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 = 'Mumbai'; // Throws at runtime
Use final or var instead.
final cities = ['Delhi', 'UP', 'Noida']; cities = '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.