initializer_for_static_field 진단: 생성자에서 static 필드 초기화 규칙

initializer_for_static_field 진단: 생성자에서 static 필드 초기화 규칙

Dart 분석기가 만들어 내는 initializer_for_static_field 진단에 대한 설명이에요.

출처: initializer_for_static_field

본문

{0}는 둘러싼 클래스의 static 필드예요. 생성자에서 초기화되는 필드는 static일 수 없어요.

설명

분석기는 static 필드를 초기화 형식 매개변수(initializing formal parameter)를 통해 초기화하거나, 이니셜라이저 리스트에서 대입문으로 초기화할 때 이 진단을 만들어요.

예시

다음 코드는 static 필드 a가 초기화 형식 매개변수 this.a에 의해 초기화되기 때문에 이 진단을 만들어요.

class C {
  static int? a;
  C(this.a);
}

흔한 해결 방법

필드가 인스턴스 필드가 되어야 한다면 static 키워드를 제거해요.

class C {
  int? a;
  C(this.a);
}

인스턴스 필드를 초기화하려던 것이고 이름을 잘못 적었다면, 초기화하려는 필드의 이름을 고쳐요.

class C {
  static int? a;
  int? b;
  C(this.b);
}

정말로 static 필드를 초기화하고 싶다면, 초기화를 생성자 본문 안으로 옮겨요.

class C {
  static int? a;
  C(int? c) {
    a = c;
  }
}

더 알아보기