跳到主內容

const_with_non_const

呼叫的建構函式不是 const 建構函式。

描述

#

當使用關鍵字 const 呼叫未標記為 const 的建構函式時,分析器會生成此診斷資訊。

示例

#

以下程式碼會生成此診斷資訊,因為 A 中的建構函式不是 const 建構函式

dart
class A {
  A();
}

A f() => const A();

常見修復方法

#

如果希望並且可能將類設為常量類(透過將類的所有欄位,包括繼承的欄位,設為 final),則在建構函式前新增關鍵字 const

dart
class A {
  const A();
}

A f() => const A();

否則,刪除關鍵字 const

dart
class A {
  A();
}

A f() => A();