dart: what is the meaning of class constructor being marked as const
- The constructor can't have a constructor body.
- All members have to be final and must be initialized at declaration or by the constructor arguments or initializer list.
- You can use an instance of this class where only constants are allowed (annotation, default values for optional arguments, ...)
- You can create constant fields like
static const someName = const Whatever()
;
If the class doesn't have a const constructor it can't be used to initialize constant fields. I think it makes sense to specify this at the constructor. You can still create instances at runtime with new Whatever()
or add a factory constructor.
See also
- Dartlang const constructor - how is it different to "regular" constructor
- Dart factory constructor - how is it different to “const” constructor
- How to make a factory constructor that returns as const value
- Why does Dart have compile time constants?
- How to write abstract class constructors so that it will be flexible for extending in sub classes
The "old style" (still valid) enum is a good example how to use const https://stackoverflow.com/a/15854550/217408