Reputation: 287
I have a class with multiple named constructors. All of them have a set of defined parameters and for now I have to rewrite them all over again when I add a new named constructor.
Is there a way to reduce the boilerplate of the below code to not enter all parameters over again ?
class Person {
final String name;
final String lastName;
final String login;
final String anotherValue;
final String address;
final int age;
final String _text;
const Person.sayHello(
this.name,
this.age,
this.lastName,
this.login,
this.anotherValue,
this.address,
) : _text = "Hello";
const Person.sayBye(
this.name,
this.age,
this.lastName,
this.login,
this.anotherValue,
this.address,
) : _text = "Bye";
void readText() {
debugPrint(_text);
}
}
I tried with abstract or extend method but I don't find a proper way to do it.
Upvotes: 0
Views: 400
Reputation: 166
It may not be what you want, but we can divide the code about named constructor like this.
class Person {
const Person(
this.name,
this.age,
this.lastName,
this.login,
this.anotherValue,
this.address,
this._personText,
);
final String name;
final String lastName;
final String login;
final String anotherValue;
final String address;
final int age;
final PersonText _personText;
void readText() {
debugPrint(_personText.text);
}
}
class PersonText {
const PersonText.sayHello() : text = 'Hello';
const PersonText.sayBye() : text = 'Bye';
final String text;
}
You can also replace it like this.
enum PersonText {
hello,
bye,
}
extension PersonTextHelper on PersonText {
String get text {
switch (this) {
case PersonText.hello:
return 'Hello';
case PersonText.bye:
return 'Bye';
}
}
}
Upvotes: 2