본문 바로가기

Dart

[Dart] Class - 선언 및 생성자

선언 및 생성자

 

void main() {
  
  House house1 = new House(4,2);
  house1.aboutHouse();
}

class House {
  final int? rooms;
  final int? floors;
  
  House(this.rooms, this.floors);
  
  void aboutHouse(){
    print('This house has $floors floors and $rooms rooms.');
  }
} 

--------------------------------------------[result]

This house has 2 floors and 4 rooms.

 

다른 스타일 생성자

 

void main() {
  
  House house1 = new House(4,2);
  house1.aboutHouse();
}

class House {
  final int? rooms;
  final int? floors;
  
  House(var rooms, var floors) : this.rooms=rooms, this.floors=floors;  

  void aboutHouse(){
    print('This house has $floors floors and $rooms rooms.');
  }
} 

void main() {
  
  House house1 = new House(4,2);
  house1.aboutHouse();
  
  House house2 = new House.fromMap(
    {'rooms': 5, 'floors':3,}
  );
  house2.aboutHouse();
}

class House {
  final int? rooms;
  final int? floors;
  
  House(this.rooms, this.floors);

  House.fromMap(Map input) : this.rooms=input['rooms'], this.floors=input['floors'];
  
  
  void aboutHouse(){
    print('This house has $floors floors and $rooms rooms.');
  }
} 

--------------------------------------------[result]

This house has 2 floors and 4 rooms.
This house has 3 floors and 5 rooms.

 

생성자 - 파라미터 옵션(안 넣으면 null 처리)

 

void main() {
  
  House house1 = new House(rooms:4);
  house1.aboutHouse();
}

class House {
  final int? rooms;
  final int? floors;
  
  House({this.rooms, this.floors});
  
  void aboutHouse(){
    print('This house has $floors floors and $rooms rooms.');
  }
} 

--------------------------------------------[result]

This house has null floors and 4 rooms.

 

'Dart' 카테고리의 다른 글

[Dart] Class - 상속/Inheritance  (0) 2021.05.27
[Dart] Class - getter, setter  (0) 2021.05.27
[Dart] Null Safety  (0) 2021.05.12
[Dart] Stream 처리.  (0) 2021.05.01
[Dart] Future, async-await  (0) 2021.04.30