[Flutter] Non-nullable instance field '_controller' must be initialized

임효진·2024년 4월 18일
0

이슈

목록 보기
5/5

Non-nullable instance field '_controller' must be initialized

Flutter에서 "Non-nullable instance field '_controller' must be initialized."라는 에러는 Dart 언어의 null safety 기능으로 인해 발생한다.
이 오류는 _controller라는 필드가 non-nullable로 선언되었지만,
객체가 생성될 때 적절히 초기화되지 않았을 때 나타나는 것이다.

Flutter의 StatefulWidget에서는 특히 AnimationController와 같은 객체를
클래스의 상단에서 직접 초기화하지 않고, initState() 메소드에서 초기화하는 패턴이 자주 사용된다.
이 경우, 해당 필드를 late 키워드를 사용하여 나중에 초기화될 것임을 명시해야 한다.

  AnimationController _controller;
  Animation<double> _animation;

해결 방법

late 키워드 사용:
AnimationController 인스턴스를 선언할 때 late 키워드를 사용하면, Dart 컴파일러에게 해당 변수가 initState()에서 초기화될 것이라고 알릴 수 있다.
이 방법은 변수가 실제 사용되기 전에 반드시 초기화될 것이라는 것이 보장될 때 사용할 수 있다.

선언과 동시에 초기화:
가능하다면, 변수를 선언할 때 바로 초기화하는 방법도 있다.
하지만 AnimationController의 경우 this context에 접근해야 하므로 initState()에서 초기화하는 것이 일반적이다.

  late AnimationController _controller;  // 'late' 키워드 추가
  late Animation<double> _animation;     // 'late' 키워드 추가
profile
네트워크 엔지니어에서 풀스택 개발자로

0개의 댓글