IT News/Flutter & Dart

플러터(flutter) dart 언어에서 Non-nullable 타입, 물음표가 있는 이유? null safety

skyLove1982 2022. 3. 2. 09:37
반응형

다트(dart) 언어에서는

널(null) 값을 사용하지 않도록 하게 되어있습니다.

그런데 null 값을 사용해야하는 경우가 있는데요.

아래 코드에는 int 로 선언된 변수 a 를 보시면

int 옆에 ? 표가 있는데요.

그 의미는 a 가 null 이 될 수 있다라는 것을 의미합니다. 

void main() {
  int? a;
  a = null;
  print('a is $a.');
}

그래서 a = null; 이 가능합니다.

즉 변수타입 옆에 물음표(?)가 있는 변수들은

null 이 될 수 있다라는 것을 의미합니다.

 

아래의 링크는 참고 주소입니다.

 

https://dartpad.dev/workshops.html?webserver=https://dartpad-workshops-io2021.web.app/null_safety_workshop 

 

DartPad Workshops

 

dartpad.dev

Non-nullable types

When you opt in to null safety, all types are non-nullable by default. For example, if you have a variable of type String, it will always contain a string.

If you want a variable of type String to accept any string or the value null, give the variable a nullable type by adding a question mark (?) after the type name. For example, a variable of type String? can contain a string, or it can be null.

Exercise:

The variable a below is declared as an int. Try changing the value in the assignment to 3 or 145. Anything but null!

반응형