dart (flutter) 문법 - null 관련 문법 정리.
dart문법에서 아래 키워드를 코드와 주석으로 설명 합니다.
? ! ?? ??= ?. ?..https://dartpad.dev 에 아래 코드를 복사해서 실행해 보세요.
void main() {
String? strTest; // '?'는 null이 가능하다는 표시.
// '!'는 strTest가 null이 아니라는 표시.
// Uncaught TypeError 예외가 난다.
//print("'!' $strTest!");
print(strTest); // null을 print하면 null 출력한다.
strTest = "test";
print(strTest);
// getString() {} 은 null을 리턴할 수 있다는 암시적 표현이다.
print("'getString()' ${getString()}");
// String? getString2() {} 은 null을 리턴할 수 있다는 명시적 표현이다.
print("'String? getString2()' ${getString2()}");
// String getString3() {} 은 반드시 String을 리턴하는 명시적 표현으로
// return "test" 가 없으므로 예외가 난다.
int? nInt;
int res = nInt ?? 5; // '??'는 nInt가 null이면 5를 반환한다.
print("'??' $res");
nInt ??= 5; // '??='는 nInt가 null이면 nInt에 5를 할당한다.
print("'??=' = $res");
List<int>? nList; // '?.'는 nList이 null이 아니면 length를 실행한다.
print("'?.' = ${nList?.length}");
// Cascade 캐스케이드
// '?..'는 nList이 null이 아니면
// 멤버변수, 필드를 순차적으로 호출할 수 있다.
nList
?..reversed
..first
..length
..isEmpty;
}
getString() {}
String? getString2() {}
// String getString3() {}
참조.
https://dart.dev/guides/language/language-tour
https://dart.dev/null-safety/understanding-null-safety
댓글
댓글 쓰기