Skip to content

prefer_type_over_var

v0.3.0 Warning Fix Type Annotations

Flags variables declared with the var keyword instead of an explicit type annotation. Using var can make it harder to understand the type of a nickname, especially when the initializer is complex or the nullability is not obvious. This rule does not flag final or const declarations.

Explicit type annotations improve code readability and make the type system work for you. When a nickname is declared with var, readers must mentally resolve the initializer to understand the type, which slows down code review and increases the chance of subtle bugs around nullability or unexpected inference.

See also: Effective Dart - Type annotations

var nickname = lookupNickname();
var anotherVar = 'string';
var number = 42;
var list = [1, 2, 3];
for (var i = 0; i < 10; i++) {
print(i);
}
var cachedNickname = lookupNickname();
String? nickname = lookupNickname();
String anotherVar = 'string';
int number = 42;
List<int> list = [1, 2, 3];
for (int i = 0; i < 10; i++) {
print(i);
}
String? cachedNickname = lookupNickname();
// final and const are allowed:
final inferred = lookupNickname();
const text = 'hello';

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.