Dart: Constant Constructor

Dart: Constant Constructor

Define a Constant Constructor and make sure that all instance variable are final.

Syntax:

class Display{
    final int x;
    const Display(this.x, ...);

Basically, Constant Constructor have no body.

Example:

Here is the example using Constant Constructor:

Instead of const you can use new keyword , Output remains the same. However, when there is only one object, both the 'new' keyword and the 'const' keyword are used.

Difference between const and new keyword:

const:

  • When we create a display constant constructor as you can see above, it is stored in the memory location below the 'const' keyword.

  • When we create an object using the 'const' keyword, let's say obj1, the reference to this location will be stored in obj1, and the same reference will also be stored in obj2.

  • Therefore, the output should be true

new:

  • When we create an object using the new keyword, it creates a new reference in memory, thus providing a different reference for obj2, hence allowing us to observe differences between the two.