跳到主要內容

prefer_const_literals_to_create_immutables

穩定
提供修復

對於 @immutable 類,優先使用 const 字面量作為建構函式的引數。

詳情

#

優先對用於不可變類例項化中作為引數的列表、對映和集合字面量使用 const 例項化。

不良示例

dart
@immutable
class A {
  A(this.v);
  final v;
}

A a1 = new A([1]);
A a2 = new A({});

良好示例

dart
A a1 = new A(const [1]);
A a2 = new A(const {});

啟用

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - prefer_const_literals_to_create_immutables

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

analysis_options.yaml
yaml
linter:
  rules:
    prefer_const_literals_to_create_immutables: true