[Dart] Constant Constructors in Dart

Constant Constructors

If your class produces objects that never change, you can make these objects compile-time constants. To do this, define a const constructor and make sure that all instance variables are final.

Summary

The constant constructor is summarized as follows:

  • Constant constructor needs to be modified with the const keyword

  • The const constructor must be used for classes whose member variables are all final

  • To construct a constant instance, the defined constant constructor must be used

  • If the const modifier is not added when instantiating, even if the constant constructor is called, the instantiated object is not a constant instance.

Examples

1
2
3
4
5
6
7
8
class Constructor {
final int field;
const Constructor(this.field);
}

void main() {
const constructor = Constructor(1);
}

Cannot invoke a non-‘const’ constructor where a const expression is expected

1
2
3
4
5
6
7
8
class Constructor {
final int field;
Constructor(this.field); // without const modifier
}

void main() {
const constructor = Constructor(1); // Error: Cannot invoke a non-'const' constructor where a const expression is expected.
}

Constructor is marked ‘const’ so all fields must be final

1
2
3
4
5
6
7
8
class Constructor {
int field; // without final modifier
const Constructor(this.field);
}

void main()
const constructor = Constructor(1); // Error: Constructor is marked 'const' so all fields must be final.
}

Initialize different instance without const modifier

1
2
3
4
5
6
7
8
9
class Constructor {
final int field;
const Constructor(this.field);
}

void main() {
print("without const identical = ${identical(Constructor(1), Constructor(1))}"); // It will initialize different instance without `const` modifier.
print("with const identical = ${identical(const Constructor(1), const Constructor(1))}"); // With const modifier
}

Run it will output:

1
2
without const identical = false
with const identical = true

References

[1] Constructors - Language tour | Dart - https://dart.dev/guides/language/language-tour#constructors