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]); }}final and const are never reported
Section titled “final and const are never reported”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
Configuration
Section titled “Configuration”This rule is in the opinionated preset, so it is on with
preset: opinionated, or by name:
rules: prefer_type_over_var: trueTo turn it off again:
rules: prefer_type_over_var: falseTo keep the rule on but skip certain paths, use per-rule exclude.
Related rules
Section titled “Related rules”prefer_explicit_function_type— Prefer explicit function type annotations over the bare ‘Function’ type.prefer_explicit_type_arguments— Pin the type arguments of the APIs where inference surprises.prefer_async_callback— Use ‘AsyncCallback’ instead of ‘Future<void> Function()’.prefer_equatable_mixin— Prefer using EquatableMixin instead of extending Equatable.