0

I know that in C++ we could have both of the constructors without a problem. In Dart when I'm trying to write two constructors, it says "The default constructor is already defined"

class Human {
  double height;
  int age;

  Human()
  {
    height = 0;
      age = 0;
  }

  Human (double startingheight){        //The default constructor is already defined
    height = startingheight;
  }

}
Aeden Thomas
  • 63
  • 1
  • 5

3 Answers3

1

Dart doesn't support methods/functions overload and will not have it in any visible future.

What you can do here is to make the parameters optional with default value:

Either as positional arguments:

class Human {
  double height = 175;
  Human([this.height]);
}

var human1 = Human(); 
var human = Human(180);

or named:

class Human {
  final double height;
  Human({this.height = 175});
}

var human1 = Human(); 
var human = Human(height: 180);
Andrey Ozornin
  • 1,129
  • 1
  • 9
  • 24
0

Try these

//Using Default parameter values
Human({this.height = 0.0, this.age = 0});

// Named constructor
Human.startingHeight(double startingHeight){ 
    height = startingHeight;
    age = 0;//or don't use this if you want it null
}

For more info check out this page: https://dart.dev/guides/language/language-tour

Er1
  • 2,559
  • 1
  • 12
  • 24
0
class Human{
      Human(double height, int color) {
      this._height = height;
      this._color = color;
   }

   Human.fromHuman(Human another) {
      this._height = another.getHeight();
      this._color = another.getColor();
   }  
}

new Human.fromHuman(man);

This constructor can be simplified

Human(double height, int age) {
   this._height = height;
   this._age = age;
}

to

Human(this._height, this._age);

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

Constructors with final fields initializer list are necessary:

class Human{
  final double height;
  final int age;

  Human(this.height, this.age);

  Human.fromHuman(Human another) :
    height= another.height,
    age= another.age;
}