본문 바로가기

Flutter/Dart

Dart 클래스 classes (1)

 

✅ 클래스 속성 정의하기

클래스의 속성(property)을 선언할 때는 타입을 반드시 명시해야 된다
(함수 내에서 타입을 명시하지 않아도 되는 var과는 다르다.)

 class Player {
  final String name = 'nico'; // String 타입의 property 정의
  int xp = 1500;
}

void main() {
  // class의 instance, 즉 object 생성!
  var player = Player(); // `new`를 사용하지 않아도 된다!
  print(player.name); // "nico"
}

✅ this는 웬만하면 사용하지 않는다!

Dart에서는 this를 잘 사용하지 않아.
하지만 지역 변수와 클래스의 속성 이름이 겹칠 경우 사용!

class Player {
  String name = 'nico';

  void sayHello1() {
    print("Hi my name is $name"); // this 없이 사용 가능!
  }

  void sayHello2() {
    var name = 'lalala';
    print("Hi my name is ${this.name}"); // 지역 변수와 클래스 속성이 겹칠 경우 사용!
  }
}

✅ 생성자 (Constructor)

Dart에서 생성자 함수는 클래스 이름과 동일해야 한다.

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

  // 클래스 이름과 같아야 생성자로 인정받는다!  
  Player(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

 

🙌 이 코드는 이렇게 줄일 수 있다!

class Player {
  final String name;
  final int age;

  Player(this.name, this.age); // 이렇게 쓰면 자동으로 값이 할당돼!
}

 

이미 string이랑 int를 위에 선언했는데 다시 할 필요가 없기 때문

 


✅ 생성자에서 많은 인자를 받을 경우?

클래스의 속성이 많아지면, 생성자가 너무 복잡해져서 가독성이 떨어질 수 있다.
예를 들어,

class Team {
  final String name;
  int age;
  String description;

  Team(this.name, this.age, this.description);
}

void main() {
  var myTeam = Team("jisoung", 17, "Happy coding is end coding");
  // 헉 😵 너무 많은 인자를 받아야 해서 헷갈려!
}

 

👀 이 문제를 해결하려면?

  1. 중괄호 {}를 이용해서 named parameters 사용하기!
class Team {
  final String name;
  int age;
  String description;

  Team({required this.name, required this.age, required this.description});
}

void main() {
  var myTeam = Team(
    name: "jisoung",
    age: 17,
    description: "Happy coding is end coding"
  ); 
  // 한눈에 들어와서 훨씬 보기 좋아! 👀
}
  1. 기본값을 주거나 required를 사용해서 null 방지하기!
class Team {
  final String name;
  int age;
  String description;

  Team({
    required this.name,
    required this.age,
    this.description = "No description",
  });
}

✅ Named Constructor & Positional Parameters

Dart에서는 Named ConstructorPositional Parameters를 지원해.
좀 더 직관적인 생성자 선언을 도와주는 문법이야!

🟢 Named Constructor (이름 있는 생성자)

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

  // 일반적인 방법  
  Player.createRed(String name, int xp)
      : this.name = name,
        this.xp = xp,
        this.team = 'red';
        
void main() {
  var player1 = Player.createBlue(name: "Nico", xp: 1500);
  print("이름: ${player1.name}, 경험치: ${player1.xp}, 팀: ${player1.team}");
}
//실행결과 이름: Nico, 경험치: 1500, 팀: blue

 

  // 간소화된 방법!  
  Player.createRed(
    this.name,
    this.xp,
    [this.team = 'red'], // 대괄호 `[]`를 사용하면 선택적 매개변수!
  );
}

void main() {
  var player1 = Player.createBlue(name: "Nico", xp: 1500);
  print("이름: ${player1.name}, 경험치: ${player1.xp}, 팀: ${player1.team}");
}
// 실행결과 : 이름: Lily, 경험치: 2000, 팀: red

 

Dart에서 :(콜론)은 초기화 리스트(initializer list) 를 나타내는 문법

위 내용으로 보면 createBlue에 사용자가 아무 값도 넣지 않는다면 초기화하여 blue로 출력이 된다.

 

🔵 선택적 Positional Parameters (위치 기반 파라미터)

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

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

  // 선택적 위치 매개변수 (team은 선택적!)
  Player.createRed(
    this.name,
    this.xp,
    [this.team = 'red'], // team을 전달하지 않으면 'red' 사용
  );
}

void main() {
  var player3 = Player.createRed("Mark", 3000);
  print("이름: ${player3.name}, 경험치: ${player3.xp}, 팀: ${player3.team}");

  var player4 = Player.createRed("Jane", 2500, "blue");
  print("이름: ${player4.name}, 경험치: ${player4.xp}, 팀: ${player4.team}");
}


//실행결과 
이름: Mark, 경험치: 3000, 팀: red
이름: Jane, 경험치: 2500, 팀: blue

 

 

🎯 정리!

  • Named Constructor는 {}를 사용해서 가독성을 높임!
  • Positional Parameters는 []를 사용해서 기본값을 줄 수 있다!
  • Dart는 간소화된 방법을 추천!
기본 클래스 클래스를 정의하고 인스턴스 생성 var player = Player();
this 사용 여부 일반적으로 생략하지만, 변수명이 겹칠 때 사용 this.name = name;
기본 생성자 클래스와 동일한 이름을 가진 함수 Player(this.name, this.xp);
Named Parameters {}를 사용하여 가독성 향상 Player({required this.name, required this.age});
Named Constructor ClassName.constructorName() 형식 Player.createBlue()
Positional Parameters 위치 기반 매개변수 Player.createRed(this.name, this.xp, [this.team = 'red']);

 

반응형

'Flutter > Dart' 카테고리의 다른 글

Dart 핵심 개념 한눈에 정리! (변수, 타입, Nullable, Enum, Loop 등)  (1) 2025.03.26
Dart 클래스 classes (2)  (0) 2025.02.03
함수 | Function  (0) 2025.02.03
데이터 타입 Data Type  (0) 2025.01.31
Variables 변수  (0) 2025.01.29