跳到主要內容

implicit_super_initializer_missing_arguments

隱式呼叫的來自“{0}”的未命名建構函式具有必填引數。

描述

#

當一個建構函式隱式呼叫超類的未命名建構函式,且超類的未命名建構函式具有必填引數,並且沒有與該必填引數對應的 super 引數時,分析器會產生此診斷資訊。

示例

#

以下程式碼會產生此診斷資訊,因為類 B 中的未命名建構函式隱式呼叫了類 A 中的未命名建構函式,但類 A 中的建構函式有一個名為 x 的必填位置引數。

dart
class A {
  A(int x);
}

class B extends A {
  B();
}

以下程式碼會產生此診斷資訊,因為類 B 中的未命名建構函式隱式呼叫了類 A 中的未命名建構函式,但類 A 中的建構函式有一個名為 x 的必填命名引數。

dart
class A {
  A({required int x});
}

class B extends A {
  B();
}

常見修復方法

#

如果你可以在子類建構函式中新增引數,那麼新增一個與超類建構函式中必填引數對應的 super 引數。新引數可以是必填引數

dart
class A {
  A({required int x});
}

class B extends A {
  B({required super.x});
}

也可以是可選引數

dart
class A {
  A({required int x});
}

class B extends A {
  B({super.x = 0});
}

如果你不能在子類建構函式中新增引數,那麼新增一個帶有必填引數的顯式 super 建構函式呼叫。

dart
class A {
  A(int x);
}

class B extends A {
  B() : super(0);
}