var_ with_ no_ type_ annotation
Details about the 'var_with_no_type_annotation' diagnostic produced by the Dart analyzer.
Avoid declaring parameters with var and no type annotation.
Description
#
The analyzer produces this diagnostic when a parameter is
declared using the keyword var without a type annotation.
This pattern should be avoided as it likely will
be a compile-time error in a future version of Dart.
Beyond this, using var without an explicit type results in
the parameter having a type of dynamic,
disabling static type checking for that parameter.
Examples
#
The following code produces this diagnostic because the
parameter x is declared with var:
void f(var x) {
print(x);
}
The following code produces this diagnostic because the
initializing formal parameter x is declared with var:
class C {
int x;
C(var this.x);
}
Common fixes
#
If you know the desired type of the parameter,
then replace var with a type annotation:
void f(String x) {
print(x);
}
If you don't know or don't want any specific type for the parameter,
then replace var with a type of Object? or dynamic
to
make the lack of any more specific type explicit:
void f(Object? x) {
print(x);
}
Unless stated otherwise, the documentation on this site reflects Dart 3.11.0. Report an issue.