새소식

반응형
App/Dart

[Dart] 다트 Named constructors 알아보기 (w.Flutter)

  • -
반응형

2023-12-05


 

사진: Unsplash 의 The Cleveland Museum of Art


1. Named constructors

 

다트에서는 하나의 클래스 내의 여러 개의 생성자를 만드는 것을 허용한다. 각 생성자들은 자신만의 고유한 이름을 가지게 되는데 이게 Named constructors이다.


2. 방법

 

사용방법은 간단한다. 아래의 예제를 보자.

 

void main() {
  
  var p1 = Point.origin();
  print("${p1.x} / ${p1.y}"); //0 / 0
  
}

class Point {
  double x, y;

// Basic constructors
  Point(this.x, this.y); 

//Named constructors
  Point.origin() 
      : x = 0,
        y = 0;
}

 

Named constructors는 예제와 같이 Class 명과 명시적인 이름을 가지게 표현된다.


물론 아래와 같이 매개값을 가질 수도 있다.

 

void main() {
  
  var p1 = Point.origin();
  var p2 = Point.custom(3, 5);
  
  print("${p1.x} / ${p1.y}"); // 0 / 0
  print("${p2.x} / ${p2.y}"); // 3 / 5
  
  
}

class Point {
  double x, y;

// Basic constructors
  Point(this.x, this.y); 

//Named constructors
  Point.origin() 
      : x = 0,
        y = 0;
  
 // Named constructor: custom
  Point.custom(double x, double y)
      : x = x,
        y = y;

}

3. fromJson 

 

Flutter에서는 백엔드 서버와 통신 시 json 형태로 데이터를 받아 처리하는 경우가 많다. 때문에 fromJson이라는 이름으로 json 형태의 값을 서버로 부터 받고 이를 model 객체로 맵핑하여 처리하는 경우가 있다. 여기서의 fromJson 도 Named constructors의 하나의 형태라고 볼 수 있다.

 

void main() {
  var p1 = Point.origin();
  var p2 = Point.custom(3, 5);
  
  print("${p1.x} / ${p1.y}"); // 0 / 0
  print("${p2.x} / ${p2.y}"); // 3 / 5

  Map<String, double> json = {'x': 2.0, 'y': 4.0};
  var p3 = Point.fromJson(json); // Creating Point from JSON
  print("${p3.x} / ${p3.y}"); // 2 / 4
}

class Point {
  double x, y;

  // Basic constructor
  Point(this.x, this.y); 

  // Named constructor: origin
  Point.origin() 
      : x = 0,
        y = 0;

  // Named constructor: custom
  Point.custom(double x, double y)
      : x = x,
        y = y;

  // Named constructor: fromJson
  Point.fromJson(Map<String, double> json)
      : x = json['x']!,
        y = json['y']! {
    print('In Point.fromJson(): ($x, $y)');
  }
}

4. 출처

https://dart.dev/codelabs/dart-cheatsheet

 

Dart cheatsheet codelab

Interactively learn (or relearn) some of Dart's unique features.

dart.dev


메인 이미지 출처 : 사진: UnsplashThe Cleveland Museum of Art

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.