跳到主要内容

const_constructor_with_non_final_field

不能为带有非 final 字段的类定义 const 构造函数。

描述

#

当构造函数被标记为 const 构造函数,但该构造函数定义的类至少有一个非 final 实例字段(直接或继承)时,分析器会产生此诊断信息。

示例

#

以下代码会产生此诊断信息,因为字段 x 不是 final 的

dart
class C {
  int x;

  const C(this.x);
}

常见修复

#

如果可以将所有字段标记为 final,请这样做

dart
class C {
  final int x;

  const C(this.x);
}

如果不能将所有字段标记为 final,请从构造函数中移除 const 关键字

dart
class C {
  int x;

  C(this.x);
}