dart const static fields dart const static fields dart dart

dart const static fields


You could, in theory, change Dart so that the const modifier implies static. This is a valid proposal and was actively discussed.

There are two reasons why we prefer requiring the explicit static:

  • It makes it clearer how these variables can be accessed (like any other static).
  • We might want to use instance const for a different meaning. At the moment, const instance fields are strictly equivalent to final fields. However, they do not need to be. You could, for example, change the Dart spec to allow access to const instance fields as part of a constant expression. (Currently it is not allowed to access fields on the right-hand side of const fields.)

As example for the second point. Say you have:

class Point {   final int x;   final int y;   const Point(this.x, this.y);}const origin = Point(0, 0);

Currently, you wouldn't be able to write:

const origin_x = origin.x;

One could change the spec to allow constant accesses to fields of constant objects, but this would hinder the evolution of const classes.For example, changing the field to a getter would suddenly be a breaking change.

The const proposal marks those fields, thus allowing access to them in const contexts. At the same time the author of the class knows that changing the field (for example into a getter) would be a breaking change.

class Point {   const int x;   const int y;   const Point(this.x, this.y);}const origin = Point(0, 0);const origin_x = origin.x;  // Now allowed.