dartconstants

What is the "const" keyword used for in Dart?


Can someone explain to me how/when/why to use const keyword, or it is just "a way to declare a constant variable"? If so, what's the difference between this :

int x = 5;

and

const int x = 5;

Could you guys please give me an example?


Solution

  • const means compile time constant. The expression value must be known at compile time. const modifies "values".

    From news.dartlang.org,

    "const" has a meaning that's a bit more complex and subtle in Dart. const modifies values. You can use it when creating collections, like const [1, 2, 3], and when constructing objects (instead of new) like const Point(2, 3). Here, const means that the object's entire deep state can be determined entirely at compile time and that the object will be frozen and completely immutable.

    if you use

    const x = 5 then variable x can be used in a const collection like

    const aConstCollection = const [x];
    

    if you don't use const, and just use x = 5 then

    const aConstCollection = const [x]; is illegal.

    More examples from www.dartlang.org

    class SomeClass {
      static final someConstant = 123;
      static final aConstList = const [someConstant]; //NOT allowed
    }
    
    class SomeClass {
      static const someConstant = 123; // OK
      static final startTime = new DateTime.now(); // OK too
      static const aConstList = const [someConstant]; // also OK
    }