Why is it not possible to declare a constant variable as a member
variable in Dart?
Lets first define what member or instance variables are. Instance variables are basically things that define properties of an object. So, an object of a Car
class made like Car(name: "Mercedeces", price: 500000)
will have different member property values than Car(name: "Toyota", price: 10000)
.
Now having an instance variable as final
basically means that once you define a Car
object with name Mercedes
you absolutely can not change the name of the object at run time. You suppose need a Car
with name BMW
so make a new object. This makes sense when allowing instance properties as final
.
Now, lets look at const
. const
are compile time constants. Suppose you are allowed to define the name
instance variable of Car
as const
. Doing this basically means, no matter how many instances you create of the Car
object, all of the names will be the same and just like final
members you cannot change it. The first part sounds odd. Not all cars will have the same name
, that is contradictory to what instance or object of a class means. A object property may be immutable, using final
but definitely will not have the same values. You would want to be able to makes instances of Mercedes
sometimes and BMW
sometimes. So, it makes no sense to make a instance property as const
. This is why dart doesn't allow const
without a static keyword. You need a static
keyword beside a const
property inside a class because only then it conforms to the definition of instance properties.