Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

flutter - Dart Multiple Constructors

Is it really not possible to create multiple constructors for a class in dart?

in my Player Class, If I have this constructor

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

Then I try to add this constructor:

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

I get the following error:

The default constructor is already defined.

I'm not looking for a workaround by creating one Constructor with a bunch of non required arguments.

Is there a nice way to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can only have one unnamed constructor, but you can have any number of additional named constructors

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);

This constructor can be simplified

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

to

  Player(this._name, this._color);

Named constructors can also be private by starting the name with _

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

  Player._foo();
}

Constructors with final fields initializer list are necessary:

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...