아래와 같이 클래스를 만들면서 상수를 생성자에 넣는 경우가 생길 수 있다.
class Cleric {
static const int maxHp = 50;
static const int maxMp = 10;
String name;
int hp;
int mp;
Cleric({required this.name, this.hp = maxHp, this.mp = maxMp});
}
그런데 final로 선언한 상수도 되지 않을까? 하고 생성자 파라미터에 넣어봤더니
class Cleric {
// 이렇게도 상수를 만들 수 있다.
static final int maxHp = 50;
static final int maxMp = 10;
String name;
int hp;
int mp;
Cleric({required this.name, this.hp = maxHp, this.mp = maxMp});
}
오류가 발생했다. 왜일까?
같은 상수인데 생성자에 static final을 넣을 수 없는 이유는,
final은 런타임에서 읽히고, 생성자는 컴파일 타임에서 먼저 읽기 때문에 동일하게 런타임에서 읽히는 const 상수를 써줘야 한다.
런타임과 컴파일 타임에 대한 설명은 이전에 썼던 글 링크로 대체하겠다.
'Flutter' 카테고리의 다른 글
| [Flutter/Android] USB로 연결된 프린터 동작 구현하기 - Usb Manager (1) | 2024.11.23 |
|---|---|
| [flutter/dart] const 와 final 의 차이점 (1) | 2024.03.06 |
| 컴파일 타임과 런타임, 컴파일 에러와 런타임 에러에 대해 알아보자 (0) | 2024.03.06 |
| 객체지향형 프로그래밍과 절차지향형 프로그래밍 그리고 함수형 프로그래밍 (1) | 2024.03.06 |
| [Flutter] M1 Mac에서 ios pod install 에러 해결 (0) | 2023.08.05 |