Skip to content

local_declared_outside_its_block

Reports a local variable declared outside the one inner block that uses it. Declare it at the start of that block.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

A local variable declared in a block of which only one inner block uses it, where moving the declaration to the start of that block changes nothing that runs. The violation is on the variable’s name.

Moving it changes nothing when the variable has no initializer, or one that does nothing and cannot throw:

  • literals, constants, const creations, and collection literals of such values;
  • locals and parameters, none of them written before the inner block or captured by a closure of the function;
  • + - * /, comparisons, == != on core values, && || ??, !, unary minus, conditionals and is.

It does not report:

  • a variable used outside the inner block, or in two blocks;
  • an initializer that calls, reads a getter or a field, indexes, casts, uses ~/ or %, or interpolates a value of no core type;
  • an inner block that is the body of a loop or a function literal, or is inside one: the declaration would run once per pass or call. An enclosing block that runs once is taken instead.
  • a single statement without a block;
  • a late variable, or a declaration of two variables;
  • an inner block that declares a name the initializer reads, or the variable’s own name.

A reader carries the variable through the code before the inner block, only to learn that just that block needs it. Declared at the start of the block, it says where it is needed.

Violating
void show(bool total, int sum) {
const label = 'Total';
if (total) {
print('$label: $sum');
}
}
Corrected
void show(bool total, int sum) {
if (total) {
const label = 'Total';
print('$label: $sum');
}
}

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
enabled true false switches the rule off for the whole project.
exclude [] Path globs where the rule is silent.

Write why on the line directly above the suppression:

// Why it stays as written here.
// ignore: local_declared_outside_its_block

// ignore_for_file: assay/local_declared_outside_its_block silences it in a whole file, and // ignore: assay/local_declared_outside_its_block with the prefix works too. See Suppressions.