Is it possible to have dataful named contructors like Animal.dog() and Animal.cat() and an utility named constructor like Animal.specie() used to switch between dataful named constructors?
I came up with this because I find myself writing long switches in the middle on Widgets and I think hiding this inside the class definition would be better. Probably there is an OOP concept I'm missing here, so if there is an easier solution I don't see please, let me know.
enum AnimalsEnum { dog, cat }
class Animal {
final int age;
final String data;
final AnimalsEnum specie;
Animal(this.age, this.data, this.specie);
Animal.bySpecie(this.age, this.specie) {
switch (specie) {
case AnimalsEnum.dog:
this = Animal._dog(this.age); // Does not work
break;
case AnimalsEnum.cat:
this = Animal._cat(this.age); // Does not work
break;
}
}
Animal._dog(this.age)
: specie = AnimalsEnum.dog,
data = 'Dogs love Flutter';
Animal._cat(this.age)
: specie = AnimalsEnum.cat,
data = 'Cats love pasta';
}
CodePudding user response:
Yes you can easily obtain this result by using a factory
constructor.
Code
class Animal {
final int age;
final String data;
final AnimalsEnum specie;
Animal({required this.age, required this.data, required this.specie});
factory Animal.dog(int age) {
return Animal(
age: age,
data: 'Dogs love Flutter',
specie: AnimalsEnum.dog,
);
}
factory Animal.cat(int age) {
return Animal(
age: age,
data: 'Cats love pasta',
specie: AnimalsEnum.cat,
);
}
factory Animal.bySpecie({
required int age,
required AnimalsEnum specie,
}) {
switch (specie) {
case AnimalsEnum.dog:
return Animal.dog(age);
case AnimalsEnum.cat:
return Animal.cat(age);
}
}
}
Example
void main() {
final cat = Animal.cat(1);
final dog = Animal.dog(2);
final specie = Animal.bySpecie(age: 3, specie: AnimalsEnum.cat);
print('${cat.age} - ${cat.data} - ${cat.specie}');
print('${dog.age} - ${dog.data} - ${dog.specie}');
print('${specie.age} - ${specie.data} - ${specie.specie}');
}
Output
1 - Cats love pasta - AnimalsEnum.cat
2 - Dogs love Flutter - AnimalsEnum.dog
3 - Cats love pasta - AnimalsEnum.cat