Skip to main content

prefer_typing_uninitialized_variables

An uninitialized field should have an explicit type annotation.

An uninitialized variable should have an explicit type annotation.

Description

#

The analyzer produces this diagnostic when a variable without an initializer doesn't have an explicit type annotation.

Without either a type annotation or an initializer, a variable has the type dynamic, which allows any value to be assigned to the variable, often causing hard to identify bugs.

Example

#

The following code produces this diagnostic because the variable r doesn't have either a type annotation or an initializer:

dart
Object f() {
  var r;
  r = '';
  return r;
}

Common fixes

#

If the variable can be initialized, then add an initializer:

dart
Object f() {
  var r = '';
  return r;
}

If the variable can't be initialized, then add an explicit type annotation:

dart
Object f() {
  String r;
  r = '';
  return r;
}