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)
}
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);
}
You can use the named constructor for clarity to implement multiple constructors for a class.
class A{
String b,c,d;
// A(); //default constructor no need to write it
A(this.b,this.c); //constructor #1
A.namedConstructor(this.b,this.c,this.d); //another constructor #2
}
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, "");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.