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?
You can only have one unnamed constructor, but you can have any number of additional named constructors in Flutter. By using named constructor you can create multiple constructors in the same class. Each constructor will have a unique name.
There are three types of constructors: Default constructor. Parameterized constructor. Named constructor.
A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.
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; }
If your class uses final parameters the accepted answer will not work. This does:
class Player { final String name; final String color; Player(this.name, this.color); Player.fromPlayer(Player another) : color = another.color, name = another.name; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With