본문 바로가기

IT/flutter

현업 FLUTTER 개발 들어가기전 DART언어 파악하기 (***CLASS)

728x90
반응형

1.dart에서 property를 선언할 때는 타입을 사용해서 정의한다.

class Player {
   final String name = 'JH';
   final int age = 30;

   void sayName(){
   // class method안에서는 this를 쓰지 않는 것을 권장한다.
   print("Hi my name is $name")
   }
}

void main(){
// new를 꼭 붙이지 않아도 된다.
   var player =Player();
   player.@@@~~
}
2.dart에서 생성자(constructor) 함수는 클래스 이름과 같아야 한다.



class Player {
   // 이럴 때 late를 사용한다.
   late final String name;
   late final int age;
   // 클래스 이름과 같아야한다!
   Player(String name, int age){
      this.name = name;
      this.age= age;
   }

   // 이렇게도 사용가능
   final String name;
   final int age;

   Player(this.name, this.xp);
}

void main(){
// Player 클래스의 인스턴스 생성!
var player = Player("jisoung", 1500);
3. 함수에서 사용했던 named Parmeters 적용가능 (변수를 할당해서 사용)

class Player {
   final String name;
   int age;
   String team;

   Player({
      required this.name,
      required this.age,
      required this.team,
   }); //{} 추가하기

   void sayHello(){
       print("Hi my name is $name")
   }
}

void main(){
   //var player = Player("nudge", 1, 'red');
   var player = Player(
   name : "nudge",
   int : 1,
   team : 'red',
   )
   player.sayHello();
}
4. Named Constructor (메서드생성)

Named parameters
// 일반적인 방법
Player.createBlue({
required String name,
required int xp
}) : this.name = name,
this.xp = xp,
this.team = 'blue';

// 간소화된 방법(dart는 간소화된 방법을 추천)
Player.createRed({
required this.name,
required this.xp,
this.team = 'red',
});

positional parameters
// 일반적인 방법
Player.createRed(String name, int xp)
: this.name = name,
this.xp = xp,
this.team = 'red';

// 간소화된 방법
Player.createRed(
this.name,
this.xp,
[this.team = 'red']
);
5.

void main(){

var jisoung = Player(name: "jisoung", age: 17, description: "Happy code is end coding");

jisoung.name = "nico";

jisoung = 20;

jisoung.description = "Best Project is End Project";

}



위를 보면 반복되는 부분이 있다. dart에서는 이걸 간단하게 ..으로 해결할 수 있다.



void main(){

var jisoung = Player(name: "jisoung", age: 17, description: "Happy code is end coding");

...name = "nico"

..age = 20

..description = "Best Project is End Project";

}



각 '..'들은 jisoung을 가리킨다. 매우 유용한 operator이다.

앞에 class가 있다면 그 클래스를 가리킨다.



6.enum은 우리가 실수하지 않도록 도와주는 타입이다.

enum Team {
   red,
   blue,
}
class Player {
   String name;
   int age;
   Team team;

   Player({
       required this.name,
       required this.age,
       required this.team,
   });
}

void main(){
var jisoung = Player(name: "jisoung", age: 17, team: Team.red);
var sushi = jisoung
..name = "sushi"
..age = 12
..team = Team.blue;

728x90
반응형