noSuchMethod method Null safety
- Invocation invocation
override
This noSuchMethod() handler is called for all unknown methods called on our Chalk object. Thisd allows using user defined colors and x11 colors as 'pseudo' methods. dynamic chalk2 = Chalk(); print(chalk2.orange('Yay for red on yellow colored text!')); print(chalk.csscolor.lightskyblue('Yay for lightskyblue colored text!')); Background: https://github.com/dart-lang/sdk/blob/master/docs/language/informal/nosuchmethod-forwarding.md Good stuff.
Implementation
@override
dynamic noSuchMethod(Invocation invocation) {
// memberName will toString() like 'Symbol("orange")', so just get the name
// out of it
String methodName = invocation.memberName.toString();
methodName = methodName
.substring('Symbol("'.length, methodName.length - 2)
.toLowerCase();
bool backgroundColor = false;
if (methodName.startsWith('on') || methodName.startsWith('bg')) {
backgroundColor = true;
methodName = methodName.substring(2);
}
var rgb = ColorUtils.rgbFromKeyword(methodName);
Chalk thisColor = makeRGBChalk(rgb[0], rgb[1], rgb[2], bg: backgroundColor);
if (invocation.positionalArguments.isNotEmpty) {
// Send all the args in and chalk them up like a other normal methods
// would with call().
return thisColor.call(invocation.positionalArguments);
} else {
// Just return the chalk we just made.
return thisColor;
}
}