본문 바로가기
Flutter

[Flutter] Stream Builder에서 TypeError (Null check operator used on a null value) 가 뜨는 경우 해결법

by 김무스비 2024. 11. 10.
728x90
반응형

오늘은 Flutter Builder에서 StreamBuilder 를 사용하다가 TypeError (Null check operator used on a null value) Exception이 발생한 원인(추측)과 해결방법에 대해 남겨보고자 함니다

아직 공부중인 단계라 틀렸다면 댓글로 가르침 주시면 감사하겠슴니다 꾸벅 (__)


body: StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection('collection1/document1/collection2')
              .snapshots(),
          builder: (context, snapshot) {
              final docs = snapshot.data!.docs 
/// 중략 ////
}
)
 
 

현재 위와 같이 snapshot.data! 로 not null 선언이 되어있는데도  Null check operator used on a null value 에러가 발생하고 있습니다.

 

<추정 원인>

!로 not null 선언을 해주는 건 런타임 이전 컴파일 시점에서 not null 선언을 해주는 것이라 런타임 시에 null인 것에 대해서는 커버 해주지 못해서 생긴 것

 

<해결 방법 1 : snapshot.connectionState 활용하기>

StreamBuilder의 builder 프로퍼티에서 snapshot.connectionState를 활용해서, 데이터가 들어오기 전 상황( (=connectionState가 waiting) 에 대한 처리를 다음과 같이 해준다. 

 builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }

 

<해결 방법 2 : snapshot.hasData 활용하기>

StreamBuilder의 stream의 snapshot.hasData를 활용해서 데이터가 들어왔는지 여부에(snapshot.hasData true/false 여부) 에 따른 분개를 해준다.

builder: (context, snapshot) {
            if (snapshot.hasData) {
//true 일 경우 실행해줄 부분//
            } else {
//false일 경우 CircularProgressIndicator 사용
              return const CircularProgressIndicator();
            }

 

728x90
반응형