mustBeConst top-level constant
Annotation on a parameter whose arguments must be constants.
The Dart type system does not allow distinguishing values of constant expressions from other values of the same type, so a function cannot ask to have only constant values as arguments. This annotation marks a parameter as requiring a constant expression as argument. The analyzer can warn, or err if so configured, if a non-constant expression is used as argument.
The annotation can be applied to any parameter, but if it is applied to a parameter of an instance member, subclasses overriding the member will not inherit the annotation. If the subclass member also wants a constant argument, it must annotate its own parameter as well.
Notice that if an annotated instance member overrides a superclass member where the same parameter is not annotated with this annotation, then a user can cast to the superclass and invoke with a non-constant argument without any warnings.
An example use could be the arguments to functions annotated with RecordUse, as only constant arguments can be made available to the post-compile steps.
import 'package:meta/meta.dart' show mustBeConst;
void main() {
f();
A().i = 3;
}
const v = 3;
int f() => g(v);
int g(@mustBeConst int value) => value + 1;
class A {
int? _i;
int? get i => _i;
set i(@mustBeConst int? value) {
_i = value;
}
}
The analyzer might not recognize all constant expressions as such in a
non-constant context. Only obvious constant expressions such as const
object creation expressions, constant variable references, and simple
literals (like string literals without interpolations) are guaranteed to be
recognized as constants.
Implementation
const Object mustBeConst = _MustBeConst();