# error code

[dart dev docs] unchecked_use_of_nullable_value

unchecked_use_of_nullable_value

The method 'validate' can't be unconditionally invoked because the receiver can be 'null'.
Try making the call conditional (using '?.') or adding a null check to the target ('!')."

receiver가 'null'일 수 있기 때문에 'validate' 메서드를 무조건 호출할 수 없습니다.
호출을 조건부로 만들거나('?.' 사용) 대상에 null 검사를 추가('!').


# example & fixed

example

void f(String? s) {
  if (s.length > 3) {
    // ...
  }
}

이 경우, 매개변수로 받는 s가 nullable한 값이기에 flutter 2.0 업그레이드 한 경우 .length 구문에 에러로 알려줄 것


fixed

case1.

void f(String? s) {
  if (s != null && s.length > 3) {
    // ...
  }
}

s != null
→ 조건문에서 and 조건으로 체크 후 length가 null이 아닌것을 자연스레 증명


case2.

void f(String s) {
  if (s.length > 3) {
    // ...
  }
}

(String s)
→ nullable한 매개변수를 받는게 아닌 Non-nullable 타입의 매개변수 전달 받기


case3.

void f(String? s) {
  if (s!.length > 3) {
    // ...
  }
}

s!.length > 3
→ case2와 같이 검사하는 변수 유형을 변경할 수 없다면, 그리고 런타임 예외가 발생하는 리스크를 감수할 수 있다면, s값이 null값이 아니라고 다음 코드와 같이 주장 가능



Q. !.구문이 뭔데?

사전 궁금증:
첫번째 케이스였던 "and 조건으로 null 체크"와 차이점은?

unchecked_use_of_nullable_value 상황

→ 다음과 같이 edit time에서 에러로 반겨줌

case1, case3 유형 메소드 생성

case1) != 구문으로 체크

case3) !. 구문으로 위험 감수

테스트 결과

case3에 null 기입 시, run time exception
(이유: null.length 구문과 동일함, null값에는 .length 메소드가 없음)

case1에선 null 기입 시, 당연한 소리지만 조건문에 해당하지 않기에 메소드를 읽지 않음



# 번외편 ?. 구문은?


null값과 3은 비교할 수 없으니 edit-time에서 > 비교문에서 잘못됐다고 에러로 알려줌

[상세설명]

?.구문은 "변수값이 null값이 아닐때 다음 메소드 실행할래"와 동일함.


str?.length 

-> str값이 null값이 아닐때 .length 실행할래
-> str값이 null값이 이면, .length 실행안하고 null로 반환할래


full test code

https://dartpad.dev

void main() {
  boraNullableTest('null');
  boraNullableTest2('null');
}

void boraNullableTest(String? str){
  if(str != null && str.length > 3){
    print(str);
  }
}

void boraNullableTest2(String? str){
  if(str!.length > 3){
    print(str);
  }
}

void boraNullableTest3(String? str){
  if(str?.length > 3){
    print(str);
  }
}
profile
𝙸 𝚊𝚖 𝚊 𝚌𝚞𝚛𝚒𝚘𝚞𝚜 𝚍𝚎𝚟𝚎𝚕𝚘𝚙𝚎𝚛 𝚠𝚑𝚘 𝚎𝚗𝚓𝚘𝚢𝚜 𝚍𝚎𝚏𝚒𝚗𝚒𝚗𝚐 𝚊 𝚙𝚛𝚘𝚋𝚕𝚎𝚖. 🇰🇷👩🏻‍💻

0개의 댓글