parse static method
Parses a string into a Color.
Accepts rgb() and rgba() colors, in either functional or hex notation, as defined by https://developer.mozilla.org/en/docs/Web/CSS/color_value.
Implementation
// TODO(google) add support for color keywords and hsl.
static Color parse(String s) {
switch (s[0]) {
case 'r': // rgb
final match = _rgbRE.firstMatch(s);
if (match == null) break;
final values = match[1]!.split(_separatorRE);
if (values.length != 3 && values.length != 4) break;
int color(String s) {
final last = s.length - 1;
return s[last] == '%'
? 255 * int.parse(s.substring(0, last)) ~/ 100
: int.parse(s);
}
final r = color(values[0]);
final g = color(values[1]);
final b = color(values[2]);
final a = values.length == 4 ? num.parse(values.last) : 1;
_checkValues(r, g, b, a, s);
return Color.rgba(r, g, b, a);
case '#': // hex
s = s.substring(1);
// Calculate number of characters per channel.
final width = s.length == 6 || s.length == 8
? 2
: s.length == 3 || s.length == 4
? 1
: 0;
if (width == 0) break;
int hex(int position) {
final start = position * width;
final value = int.parse(s.substring(start, start + width), radix: 16);
return width == 1 ? value * 17 : value;
}
final r = hex(0);
final g = hex(1);
final b = hex(2);
final a = s.length % 4 == 0 ? hex(3) / 255 : 1;
_checkValues(r, g, b, a, s);
return Color.rgba(r, g, b, a);
}
throw FormatException('Invalid color format', s);
}