跳到主要內容

prefer_const_constructors

穩定
有可用的修復

對於常量的建構函式,優先使用 const

詳情

#

優先對常量建構函式的例項化使用 const

如果建構函式可以作為 const 呼叫以生成規範化例項,則優先這樣做。

不好

dart
class A {
  const A();
}

void accessA() {
  A a = new A();
}

dart
class A {
  const A();
}

void accessA() {
  A a = const A();
}

dart
class A {
  final int x;

  const A(this.x);
}

A foo(int x) => new A(x);

啟用

#

要啟用 prefer_const_constructors 規則,請在你的 analysis_options.yaml 檔案中的 linter > rules 下新增 prefer_const_constructors

analysis_options.yaml
yaml
linter:
  rules:
    - prefer_const_constructors

如果你使用的是 YAML 對映語法來配置 linter 規則,請在 linter > rules 下新增 prefer_const_constructors: true

analysis_options.yaml
yaml
linter:
  rules:
    prefer_const_constructors: true