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
What it reports
Section titled “What it reports”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,
constcreations, 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 andis.
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
latevariable, 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.
Example
Section titled “Example”void show(bool total, int sum) { const label = 'Total'; if (total) { print('$label: $sum'); }}void show(bool total, int sum) { if (total) { const label = 'Total'; print('$label: $sum'); }}Rule parameters
Section titled “Rule parameters”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. |
Suppressing it
Section titled “Suppressing it”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.