What you can learn in this post
1. How to declare variables in Dart
2. What is Null Safety
1. How to declare variables in Dart
[Can be overwritten later]
1st. Specify type
when? class property
void main () {
int i = 12;
i = 121212;
}
2nd. var
when? local variables in method, small functions local variables
void main () {
var name = 'la'
name = 'lalala'
}
3rd. dynamic
when? available in all types
void main () {
dynamic name;
name = 12;
name = 'nico';
name = true;
if (name is String){
name.isEmpty(); //can use functions for String
}
if (name is int){
name.isFinite(); can use functions for Integer
}
}
[Can NOT be overwritten later]
1st. final : 앱을 실행하면서 사용자가 입력하는 변수
void main () {
final String username;
}
2nd. const : 앱 스토어에 올라가기 전에 알고 있는 변수 (=has to be known BEFORE complie)
[When you DON'T KNOW THE VALUE at first]
1st. late
creating a variable without data
void main () {
late final String name;
//do something, go to api
print(name); //error. part of null safety.
name = 'nico';
}
[what is NULL Safety?]
All variables created in Dart are NOT nullable.
which means, it can NOT be NULL.
개발자들이 null 변수를 참조하는 코드를 짜더라도, dart 컴파일러에서는 오류가 없이 컴파일 된다.
그러나, run-time 도중에는 null 변수를 참조 오류가 발생한다.
즉, null 참조 오류는 Run-time error이다.
따라서, null safety를 통해 컴파일 도중에 오류를 잡을 필요가 있다
So, if you want to make your variable nullable,
you can add a question mark
ERROR
void main () {
String name = 'nico';
name = null;
}
NO ERROR
void main () {
String? name = 'nico';
name = null;
nico?.inNotEmpty; //if Nico is NOT null, give me the isNotEmpty property
}
https://nomadcoders.co/dart-for-beginners/lectures/4096
All Courses – 노마드 코더 Nomad Coders
초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!
nomadcoders.co
'스터디 > Dart' 카테고리의 다른 글
[Dart] #2.4 Maps (1) | 2024.01.10 |
---|---|
[Dart] #2.3 Collection For (0) | 2024.01.10 |
[Dart] #2.2 String interpolation '$' (1) | 2024.01.10 |
[Dart] #2.1 Lists & collection if (0) | 2024.01.10 |
[Dart] #2.0 Basic Data Types (0) | 2024.01.10 |