🐦 Flutter

Dart Named Constructor

ji-hyun 2022. 8. 12. 12:10

Named Constructor

 
Dart 에서 한 class 는 여러 constructor 를 가질 수 있는데, 특이한 점은 각 constructor 에 이름을 붙인다는 것이다.
명명된 생성자를 사용하여 클래스에 대해 여러 생성자를 구현하거나 추가 명확성을 제공한다.
 
class MyPoints {
  final int accumulatedPoint;
  final int usedPoint;
  final int expirePoint;

  MyPoints({
    required this.accumulatedPoint,
    required this.usedPoint,
    required this.expirePoint,
  });

  MyPoints.initial({
    this.accumulatedPoint = 0,
    this.usedPoint = 0,
    this.expirePoint = 0,
  });

  factory MyPoints.fromJson(Map<String, dynamic> json) {
    return MyPoints(
      accumulatedPoint: json['accumulatedPoint'],
      usedPoint: json['usedPoint'],
      expirePoint: json['expirePoint'],
    );
  }

  int get total => accumulatedPoint - usedPoint - expirePoint;

  MyPoints copyWith({
    int? accumulatedPoint,
    int? usedPoint,
    int? expirePoint,
  }) {
    return MyPoints(
      accumulatedPoint: accumulatedPoint ?? this.accumulatedPoint,
      usedPoint: usedPoint ?? this.usedPoint,
      expirePoint: expirePoint ?? this.expirePoint,
    );
  }
}

 

 

 

 

아래는 내가 간단히 테스트해본 예시이다.

 

void main() {
  var person = Person.ko();
  print(person.name);
  print(person.age);

}


class Person {
  String name;
  int? age;

  Person(this.name, this.age);

  Person.old(this.name) {
    this.age = 100;
  }

  Person.ko({this.name = 'dj', this.age = 10});
}