parseColor static method
Implementation
static Color? parseColor(String color, {RenderStyle? renderStyle}) {
color = color.trim().toLowerCase();
if (color == TRANSPARENT) {
return CSSColor.transparent;
} else if (_cachedParsedColor.containsKey(color)) {
return _cachedParsedColor[color];
}
Color? parsed;
if (color.startsWith('#')) {
final hexMatch = _colorHexRegExp.firstMatch(color);
if (hexMatch != null) {
final hex = hexMatch[1]!.toUpperCase();
// https://drafts.csswg.org/css-color-4/#hex-notation
switch (hex.length) {
case 3:
parsed = Color(int.parse('0xFF${_x2(hex)}'));
break;
case 4:
final alpha = hex[3];
final rgb = hex.substring(0, 3);
parsed = Color(int.parse('0x${_x2(alpha)}${_x2(rgb)}'));
break;
case 6:
parsed = Color(int.parse('0xFF$hex'));
break;
case 8:
final alpha = hex.substring(6, 8);
final rgb = hex.substring(0, 6);
parsed = Color(int.parse('0x$alpha$rgb'));
break;
}
}
} else if (color.startsWith(RGB)) {
bool isRgba = color.startsWith(RGBA);
String colorBody = color.substring(isRgba ? 5 : 4, color.length - 1);
final rgbMatch;
if (renderStyle != null && colorBody.contains('var')) {
final result = CSSVariable.tryReplaceVariableInString(colorBody, renderStyle);
rgbMatch = _colorRgbRegExp.firstMatch(result);
} else {
rgbMatch = _colorRgbRegExp.firstMatch(colorBody);
}
if (rgbMatch != null) {
final double? rgbR = _parseColorPart(rgbMatch[1]!, 0, 255, renderStyle);
final double? rgbG = _parseColorPart(rgbMatch[2]!, 0, 255, renderStyle);
final double? rgbB = _parseColorPart(rgbMatch[3]!, 0, 255, renderStyle);
final double? rgbO = rgbMatch[5] != null ? _parseColorPart(rgbMatch[5]!, 0, 1, renderStyle) : 1;
if (rgbR != null && rgbG != null && rgbB != null && rgbO != null) {
parsed = Color.fromRGBO(rgbR.round(), rgbG.round(), rgbB.round(), rgbO);
}
}
} else if (color.startsWith(HSL)) {
bool isHsla = color.startsWith(HSLA);
String colorBody = color.substring(isHsla ? 5 : 4, color.length - 1);
final hslMatch;
if (renderStyle != null && colorBody.contains('var')) {
final result = CSSVariable.tryReplaceVariableInString(colorBody, renderStyle);
hslMatch = _colorHslRegExp.firstMatch(result);
} else {
hslMatch = _colorHslRegExp.firstMatch(colorBody);
}
if (hslMatch != null) {
final double? hslH = _parseColorHue(hslMatch[1]!, hslMatch[2]);
final double? hslS = _parseColorPart(hslMatch[3]!, 0, 1, renderStyle);
final double? hslL = _parseColorPart(hslMatch[4]!, 0, 1, renderStyle);
final double? hslA = hslMatch[6] != null ? _parseColorPart(hslMatch[6]!, 0, 1, renderStyle) : 1;
if (hslH != null && hslS != null && hslL != null && hslA != null) {
parsed = HSLColor.fromAHSL(hslA, hslH, hslS, hslL).toColor();
}
}
} else if (_namedColors.containsKey(color)) {
parsed = Color(_namedColors[color]!);
}
if (parsed != null) {
_cachedParsedColor[color] = parsed;
}
return parsed;
}