일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- withopacity
- guideline 4.3(a)
- providernotfoundexception
- app store connect guideline
- flutter doctor -v
- youtube_player_flutter
- 에러
- tflite_flutter
- GetX
- flutter_secure_storage
- guideline 1.5
- appstore connect guideline
- .dio
- buildcontext
- exception
- permissiondeniedexception
- infinity or nan toint
- dart sdk version upgrade
- flutter_dotenv
- 채팅 메시지 정렬
- app stroe connect guideline
- Flutter
- exception caught by image resource service
- app completeness
- information needed
- AI
- 플러터
- undefined name
- appstroe connect guideline
- pub.dev
Archives
- Today
- Total
min_chan님의 블로그
[Flutter] - null safety 본문
null safety란?
- null이란 값이 존재하지 않음을 의미한다.
- 가장 많은 런타임에러가 발생하는 이유중 하나는 null때문에 발생한다. 그 문제를 해결하기 위해 null safety를 적용하는 것이다.
// null safety가 적용된 코드 안에서는 name, b 변수안에 null값을 넣어줄 수 없다.
String name = getFileName();
final b = Foo();
null값을 지정해주는 방법
- 해당 변수뒤에 ?를 넣어주면 null값을 넣어줄 수 있다.
null값이 아님을 표현하는 방법
- 첫번째 에러: List<int?>의 첫번째 아이템은 2인걸 알 수 있으나, List<int?>는 널이 가능한 값이므로 변수 b에 넣어줄 수 없다는 에러가 발생했다.
- 두번째 에러: couldReturnNullButDoesnt()가 null이 될 수 있음을 표현하고 있기 때문에 에러가 발생했다.
해결 방법
int? couldReturnNullButDoesnt() => -3;
void main() {
int? couldBeNullButIsnt = 1;
List<int?> listThatCouldHoldNulls = [2, null, 4];
int a = couldBeNullButIsnt;
// List<int?> 첫번째 값은 2임이 확실하므로 first뒤에 !를 사용하여
// null값이 확실히 아님을 나타내준다.
int b = listThatCouldHoldNulls.first!;
// couldReturnNullButDoesnt()의 리턴값이 -3임을 확실하게 알고 있으므로, 뒤에!를 붙여 null값이 아님을 나타내준다.
int c = couldReturnNullButDoesnt()!.abs();
print('a is $a.');
print('b is $b.');
print('c is $c.');
}
- ! 는 널값이 아님을 확신했을 때 사용한다.
- ! 를 사용한 코드가 널값일 경우 런타임에러가 발생한다.
Null checking
- String이 null이 가능한데 string이 null값이면 length를 반환할 수 없으므로 에러가 발생했다.
해결 방법
int getLength(String? str) {
// Add null check here
// str이 null이 아닌경우 str!.length;를 반환하고
// 그렇지 않을경우는 0을 반환한다.
if(str != null){
return str.length;
}
return 0;
}
void main() {
print(getLength('This is a string!'));
}
'Flutter' 카테고리의 다른 글
[Flutter] - Flame (0) | 2025.02.06 |
---|---|
[Flutter] - Key (0) | 2025.02.05 |
[Flutter] - TypeError: app.get is not a function (0) | 2025.01.31 |
[Flutter] - You need to call "Get.put(MyController())" or "Get.lazyPut(()=>MyController())" (0) | 2025.01.24 |
[Flutter] - Unknown flutter tag. Abandoning upgrade to avoid destroying local changes. (0) | 2025.01.23 |