Aeden Thomas
Aeden Thomas

Reputation: 63

How can I get a default and a parameterized constructor inside the same class in Dart/Flutter?

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

}

Upvotes: 0

Views: 879

Answers (3)

Er1
Er1

Reputation: 2758

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

Upvotes: 0

Fabiano Gadenz
Fabiano Gadenz

Reputation: 1

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

Upvotes: 0

Andrey Ozornin
Andrey Ozornin

Reputation: 1158

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

Upvotes: 1

Related Questions