[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 | class Constructor { |
Cannot invoke a non-‘const’ constructor where a const expression is expected
1 | class Constructor { |
Constructor is marked ‘const’ so all fields must be final
1 | class Constructor { |
Initialize different instance without const
modifier
1 | class Constructor { |
Run it will output:
1 | without const identical = false |
References
[1] Constructors - Language tour | Dart - https://dart.dev/guides/language/language-tour#constructors