目录

prefer_final_locals

Prefer final for variable declarations if they are not reassigned.

此规则自 Dart 2.0 版本起可用。

此规则提供 快速修复

_不兼容规则:unnecessary_final _

详情

#

DO prefer declaring variables as final if they are not reassigned later in the code.

Declaring variables as final when possible is a good practice because it helps avoid accidental reassignments and allows the compiler to do optimizations.

BAD:

dart
void badMethod() {
  var label = 'hola mundo! badMethod'; // LINT
  print(label);
}

GOOD:

dart
void goodMethod() {
  final label = 'hola mundo! goodMethod';
  print(label);
}

GOOD:

dart
void mutableCase() {
  var label = 'hola mundo! mutableCase';
  print(label);
  label = 'hello world';
  print(label);
}

使用方法

#

要启用 prefer_final_locals 规则,请在你的 analysis_options.yaml 文件中,在 linter > rules 下添加 prefer_final_locals

analysis_options.yaml
yaml
linter:
  rules:
    - prefer_final_locals