본문 바로가기
카테고리 없음

Dart 속성 뿌시기 #1

by ILGAEMI 2023. 1. 16.
반응형

function 이나 method 내부에 지역변수를 선언할 때 ‘var’을 사용한다.

int main(){
	var test = 'asdasd';
}

class나 property에서 선언할 때는 type을 지정해준다 String, int, char,…..등등 처럼

class Player{
  String name = 'yu';
  void sayHello(){
    print('hi my name is $name');
  }
}

dynamic은 다양한 type을 가질 수 있는 변수에 사용하는 키워드이지만 사용을 추천하지 않는다.

void main(){
  dynamic test = 'asd';//문자열로 선언을 해도
  print(test);
  test=10;//타입이 보호되지 않는다.
  print(test);
}

dynamic의 경우 json과 같이 데이터의 type을 명확하게 알 수 없을 때 사용한다.


null safety는 개발자들이 null value를 참조하지 않게 하는 것이며 null값을 받아오면 run time error를 occurred시킨다.

//특정 variable에 값을 넣는데 그 값이 string일 수도 있고 int일 수도 있다고 한다면 
id main(){
	String? nico = 'hello';//?물음표를 꼭 넣어줘야함
	nico = null;
	if (nico != null){
		nico.isNotEmpty();
	}
	nico?.isNotEmpty();//nico가 null이 아니라면 반환 값을 달라 위에 있는 if문과 동일한 결과

}

수정 불가한 변수로 선언하기 위해서라면 final로 선언해야한다.

//late modifier는 final나 var에  attached될 수 있다.
//late는 variable을 초기값 세팅 없이 declare할 수 있게 해줌
//example
void main(){
	late final String test;
	// do something, go to api
	name = 'yu';
	
}

Flutter에서 const는 compile-time constant를 만들어 줌

compile-time constant는 반드시 compile time에 알고 있어야하는 값이어야 한다.

예를들어 fetchApi()와 같이 compile time에 값을 가져오지 못하는 경우 const로는 받아올 수 없다.

 

Tip*>>Flutter 측에서도 값을 선언할 때 var형식으로 declare하는 것을 추천한다. int나 String 등과 같이 type을 초기에 설정하는 case는 class와 같이 global로 선언할 때만 추천된다.

반응형

댓글