Skip to content

prefer_type_over_var

v0.3.0 Warning Fix Type Annotations

Flags a variable declared with var instead of an explicit type annotation. final and const declarations are never reported — only the var keyword is.

The type of a var is whatever the initializer happened to return, and the reader has to go and look — which matters most where it is easiest to get wrong, around nullability:

String? findNickname(int userId) => null;
void greet(int userId) {
var nickname = findNickname(userId);
// `nickname` is String?, not String — nothing on this line says so.
print(nickname.length);
}

Top-level and for-loop declarations are reported too:

var retryCount = 3;
var pendingIds = <int>[];
void retryAll() {
for (var i = 0; i < retryCount; i++) {
print(pendingIds[i]);
}
}

Write the type. The nullability is now visible at the declaration:

String? findNickname(int userId) => null;
void greet(int userId) {
String? nickname = findNickname(userId);
print(nickname?.length);
}
int retryCount = 3;
List<int> pendingIds = <int>[];
void retryAll() {
for (int i = 0; i < retryCount; i++) {
print(pendingIds[i]);
}
}

The rule keys on the var keyword alone, so an immutable declaration with an inferred type passes as it is:

final resolved = findNickname(7);
const greeting = 'hello';
// `final` with a type is also fine, of course.
final String? explicit = findNickname(7);

See also: Effective Dart - Type annotations

This rule is in the opinionated preset, so it is on with preset: opinionated, or by name:

many_lints.yaml
rules:
prefer_type_over_var: true

To turn it off again:

many_lints.yaml
rules:
prefer_type_over_var: false

To keep the rule on but skip certain paths, use per-rule exclude.