Sometimes, constructing a class as const
has a different meaning than constructing it with new
. For example, String.fromEnvironment()
says:
This constructor is only guaranteed to work when invoked as
const
. It may work as a non-constant invocation on some platforms which have access to compiler options at run-time, but most ahead-of-time compiled platforms will not have this information.
That means that if you forget to write the const
in const String.fromEnvironment()
, you won’t get the dart-define=...
compiler flag values at runtime. And there is no warning. You just get an empty string.
But this goes beyond fromEnvironment()
. You can have a class that’s supposed to have only one const instance, such as:
/// Represents an action that does nothing.
class NoOpAction extends Action {
const NoOpAction();
void execute() {
// Pass.
}
}
And you might want to check if an action is no-op, so you want to write code like:
if (action == const NoOpAction()) ...
But that will only work if both sides of the equation are const. So you want to force the const
.
I though there was a pkg:meta
annotation for this but I can’t find this now.
@mustInstantiateAsConst // or something like that ?
const NoOpAction();
I think that the traditional way of dealing with this would be something like:
class NoOpAction extends Action {
static const instance = NoOpAction._();
const NoOpAction._();
void execute() {
// Pass.
}
}
But I’d like to avoid this because it forces the user to think (“wait, does this subclass have an .instance
static field or should I use a constructor?”) and also code completion becomes unhelpful when you have something like this (you start writing the class name but instead of the option to import the appropriate file, you get nothing — until you start typing the .instance
part).
(Also, this is different and separate from the prefer_const_constructors
lint. This is about selectively marking a constructor. The prefer_const_constructors
lint marks every such constructor use, which is not what I want — that lint is annoying and has dubious value, but that’s a separate discussion.)