Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create multiple constructors in dart?

Tags:

flutter

dart

I would like to create different objects by calling constructors that have different number of parameters. How can I achieve this in Dart?

class A{
  String b,c,d;

  A(this.b,this.c)
  A(this.b,this.c,this.d)

}
like image 208
Daniel Avatar asked Dec 10 '22 02:12

Daniel


2 Answers

See Constructor section of Tour of Dart.

Basically Dart doesn't support methods/constructor overloading. However Dart allows named constructors and optional parameters.

In your case you could have:

class A{
  String b,c,d;

  /// with d optional
  A(this.b, this.c, [this.d]);

  /// named constructor with only b and c
  A.c1(this.b, this.c);
  /// named constructor with b c and d
  A.c2(this.b, this.c, this.d);
}
like image 107
Alexandre Ardhuin Avatar answered Jan 19 '23 03:01

Alexandre Ardhuin


You can use factory constructors

class A{
  String b,c,d;

  A(this.b,this.c,this.d)
  
  factory A.fromBC(String b, String c) => A(b, c, "");
}
like image 41
faruk Avatar answered Jan 19 '23 03:01

faruk