~songbly/blog
Published on

Flutter 에서 null safety 이해하기 (3) - Type Promotion (2)

Authors

지난 포스팅 까지는, 지역 변수들에 대한 type promotion 을 알아봤다. 이번 포스팅에서는 객체 속성인 객체 필드에서의 type promotion을 살펴보자.

import 'dart:math';

class RandomStringProvider {
  String? get value =>
    Random().nextBool() ?  'A String' : null;
}

void printString(String str) => print(str);

void main() {
  final provider = RandomStringProvider();

  if(provider.value == null) {
    print('The value is null.');
  } else {
    print('The value is not null, so print it!');
    printString(provider.value);
  }
}

위 코드를 dartpad에서 실행시켜 보면, 에러가 발생하고 있다. 앞선 포스팅에서 본 내용들로만 생각하면, 분기처리도 되어있고, null 체크도 해주는 것 같은데, printString(provider.value)는 왜 에러가 발생하는 걸까?

이유는 Random().nextBool() ? 'A String' : null; 여기에 두 번 접근하면, 다른 값이 생성 될 수 있기 때문이다. 따라서 이 문제는 로컬(지역) 변수를 사용하여, 해당 값을 확인하고 사용하는 동일한 범위 내애서 해당 결과를 캐시 함으로 해결 할 수 있다. Dart는 실행 과정에서 해당 값이 변경되지 않는 다는 것을 알 수 있기 때문이다.

따라서, 아래와 같이 코드를 수정해 주면 Dart는 더이상 문제 제기를 하지 않는다.

import 'dart:math';

class RandomStringProvider {
 String? get value =>
   Random().nextBool() ?  'A String' : null;
}

void printString(String str) => print(str);

void main() {
 final provider = RandomStringProvider();

 final str = provider.value;

 if(str == null) {
   print('The value is null.');
 } else {
   print('The value is not null, so print it!');
   printString(str);
 }
}