Skip to content

Instantly share code, notes, and snippets.

@nikli2009
Last active July 4, 2019 12:40
Show Gist options
  • Save nikli2009/3aada1be09b616ba56e2ad0b71354ba9 to your computer and use it in GitHub Desktop.
Save nikli2009/3aada1be09b616ba56e2ad0b71354ba9 to your computer and use it in GitHub Desktop.
Dart Optional Named Class
void main() {
// provide only required parameter
FunnyText uselessWidget1 = FunnyText('hello');
// provide an empty named parameter
FunnyText uselessWidget2 = FunnyText('hello', style: TextStyle());
// provide a complete named parameter to override DEFAULT value, which is 20.0
FunnyText uselessWidget3 = FunnyText('hello', style: TextStyle(fontSize: 30.0));
uselessWidget1.printFontSize(); // 20
uselessWidget2.printFontSize(); // 20
uselessWidget3.printFontSize(); // 30
}
class FunnyText {
String text;
TextStyle style;
// constructor
FunnyText(String text, { TextStyle style = null}) {
TextStyle DefaultTextStyle = TextStyle(fontSize: DEFAULT_FONT_SIZE);
this.text = text;
this.style = style == null ?
DefaultTextStyle :
TextStyle.merge(defaultStyle: DefaultTextStyle, fontSize: style.fontSize);
}
void printFontSize() {
print('printFontSize - ${this.style.fontSize}');
}
}
const double DEFAULT_FONT_SIZE = 20.0;
class TextStyle {
double fontSize;
TextStyle({this.fontSize});
// override source if target has conflict value
TextStyle.merge({
TextStyle defaultStyle,
double fontSize = 0.00}) {
this.fontSize = (fontSize != null && fontSize > 0) ? fontSize : defaultStyle.fontSize;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment