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.
NOTE: This rule is removed in Dart 3.13.0; it is no longer functional.
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:
// @dart=3.12
void f(var x) {
print(x);
}
The following code produces this diagnostic because the
initializing formal parameter x is declared with
var:
// @dart=3.12
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);
}
除非另有说明,文档之所提及适用于 Dart 3.12.2 版本报告页面问题.