본문 바로가기
Flutter/Flutter FAQ

Flutter 다트 다중 생성자, Dart Multiple Constructors

by 베타코드 2023. 5. 28.
반응형

질문


다트에서 클래스에 여러 생성자를 만들 수 없는 것이 사실인가요?

내 Player 클래스에서 이 생성자가 있다면

Player(String name, int color) {
    this._color = color;
    this._name = name;
}

그런 다음이 생성자를 추가하려고하면:

Player(Player another) {
    this._color = another.getColor();
    this._name = another.getName();
}

다음 오류가 발생합니다.

기본 생성자가 이미 정의되어 있습니다.

나는 필수가 아닌 인수를 가진 하나의 생성자를 만들어 우회하는 해결책을 찾고 있지 않습니다.

이를 해결하는 좋은 방법이 있나요?


답변


하나의 이름 없는 생성자만 가질 수 있지만, 추가 이름 있는 생성자는 여러 개 가질 수 있습니다.

class Player {
  Player(String name, int color) {
    this._color = color;
    this._name = name;
  }

  Player.fromPlayer(Player another) {
    this._color = another.getColor();
    this._name = another.getName();
  }  
}

new Player.fromPlayer(playerOne);

이 생성자

  Player(String name, int color) {
    this._color = color;
    this._name = name;
  }

다음과 같이 간단하게 표현할 수 있습니다.

  Player(this._name, this._color);

이름 있는 생성자는 이름 앞에 _를 붙여 비공개로 만들 수도 있습니다.

class Player {
  Player._(this._name, this._color);

  Player._foo();
}

final 필드 초기화 리스트를 사용하는 생성자가 필요합니다:

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

  Player.fromPlayer(Player another) :
    color = another.color,
    name = another.name;
}
반응형

댓글