Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart Multiple Constructors

Tags:

flutter

dart

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?

like image 442
Tom Porat Avatar asked Apr 06 '18 10:04

Tom Porat


People also ask

Can I have multiple constructors in Dart?

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.

How many constructors can a class have in Dart?

There are three types of constructors: Default constructor. Parameterized constructor. Named constructor.

Can you have 2 constructors?

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.


2 Answers

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; } 
like image 182
Günter Zöchbauer Avatar answered Sep 16 '22 17:09

Günter Zöchbauer


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; } 
like image 29
Quentin Avatar answered Sep 20 '22 17:09

Quentin