avoid-unnecessary-local-variable

Group
Style
Path
lint/style/avoid-unnecessary-local-variable
Default
Off, opt in
Origin
Falcon
Rule
167 of 512

Reports a single-use local used only to initialize the next local. Both declarations must be eager and inferred: transferring the initializer then preserves evaluation order and its type-inference context.

Invalid

example.dartdart
void a() {
  var first = 1;
  var second = first;
  print(second);
}
void b() {
  final first = Object();
  final second = first;
  print(second);
}
void c() {
  final first = [1, 2];
  final second = first;
  print(second);
}
void d() {
  final first = true;
  final second = (first);
  print(second);
}
void e() {
  final first = DateTime.now();
  var second = first;
  print(second);
}
Initialize the next local directly instead of introducing this single-use alias.
1void a() {
2 var first = 1;
Initialize the next local directly instead of introducing this single-use alias.
6void b() {
7 final first = Object();
Initialize the next local directly instead of introducing this single-use alias.
11void c() {
12 final first = [1, 2];
Initialize the next local directly instead of introducing this single-use alias.
16void d() {
17 final first = true;
Initialize the next local directly instead of introducing this single-use alias.
21void e() {
22 final first = DateTime.now();

Valid

example.dartdart
Object immediateReturn() {
  final value = Object();
  return value;
}
void twice() {
  final first = Object();
  final second = first;
  print(first);
  print(second);
}
void typed() {
  final num first = 1;
  final second = first;
  print(second);
}
void typedAlias() {
  final first = [1];
  final List<num> second = first;
  print(second);
}
void deferred() {
  late final first = Object();
  final second = first;
  print(second);
}
void separated() {
  final first = Object();
  print('intervening');
  final second = first;
  print(second);
}
void captured() {
  var first = Object();
  final second = first;
  void change() { first = Object(); }
  print(second);
}
void thrown() {
  final error = Exception();
  throw error;
}

Configure avoid-unnecessary-local-variable

Set its severity in falcon.json. See the configuration guide.

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "avoid-unnecessary-local-variable": "error"
      }
    }
  }
}

Or silence one occurrence with a suppression comment; the reason is required.

example.dartdart
// falcon-ignore lint/style/avoid-unnecessary-local-variable: <reason>