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


댓글

이 블로그의 인기 게시물

파이썬 vscode에서 자동 코드 정렬. Formatter.

Unity3D git 저장소에 올릴때 필요없는 파일 제외하기. gitignore

플러터(flutter) 개발 참고 사이트들.