1

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?

shaby
  • 1,301
  • 1
  • 15
  • 17

4 Answers4

0

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.

Coder2195
  • 268
  • 2
  • 13
0

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
croxx5f
  • 5,163
  • 2
  • 15
  • 36
0

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.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

When you declare a list using the const keyword, it creates an immutable list, which means you cannot modify its elements or change its length. However, Dart's static analysis cannot catch this error during compilation because the add method is a valid method on a List object, and it can only be detected at runtime when you attempt to modify the immutable list.

Chatura Dilan
  • 1,502
  • 1
  • 16
  • 29