native_field_not_static 진단: native 필드는 반드시 static이어야 해요

native_field_not_static 진단: native 필드는 반드시 static이어야 해요

인스턴스 필드에 @Native 어노테이션을 붙였을 때 Dart 분석기가 알려주는 native_field_not_static 진단에 대한 설명이에요. native 필드는 C, C++ 같은 native 언어의 전역 변수를 가리키므로 항상 static이어야 해요.

출처: native_field_not_static

본문

설명

클래스의 인스턴스 필드에 @Native 어노테이션이 붙었을 때 분석기가 이 진단을 만들어요.

native 필드는 C, C++ 또는 다른 native 언어의 전역 변수를 가리키는 반면, Dart의 인스턴스 필드는 해당 클래스의 특정 인스턴스에 속해요. 그래서 native 필드는 반드시 static이어야 해요.

FFI에 대해 더 자세히 알고 싶다면 dart:ffi를 사용한 C interop 문서를 참고해요.

예시

다음 코드는 클래스 C의 필드 f@Native인데 static이 아니어서 이 진단을 만들어요.

import 'dart:ffi';

class C {
  @Native<Int>()
  external int f;
}

흔한 해결 방법

필드를 static으로 만들거나,

import 'dart:ffi';

class C {
  @Native<Int>()
  external static int f;
}

클래스 밖으로 옮겨도 돼요. 이 경우에는 명시적인 static 한정자가 필요 없어요.

import 'dart:ffi';

class C {}

@Native<Int>()
external int f;

struct의 일부가 되어야 하는 인스턴스 필드에 어노테이션을 붙이려던 의도였다면, @Native 어노테이션을 빼면 돼요.

import 'dart:ffi';

final class C extends Struct {
  @Int()
  external int f;
}

더 알아보기