parseColor static method

Color? parseColor(
  1. String color
)

Implementation

static Color? parseColor(String color) {
  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)) {
    final rgbMatch = _colorRgbRegExp.firstMatch(color);
    if (rgbMatch != null) {
      final double? rgbR = _parseColorPart(rgbMatch[2]!, 0, 255);
      final double? rgbG = _parseColorPart(rgbMatch[3]!, 0, 255);
      final double? rgbB = _parseColorPart(rgbMatch[4]!, 0, 255);
      final double? rgbO = rgbMatch[6] != null ? _parseColorPart(rgbMatch[6]!, 0, 1) : 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)) {
    final hslMatch = _colorHslRegExp.firstMatch(color);
    if (hslMatch != null) {
      final hslH = _parseColorHue(hslMatch[2]!, hslMatch[3]);
      final hslS = _parseColorPart(hslMatch[4]!, 0, 1);
      final hslL = _parseColorPart(hslMatch[5]!, 0, 1);
      final hslA = hslMatch[7] != null ? _parseColorPart(hslMatch[7]!, 0, 1) : 1;
      if (hslH != null && hslS != null && hslL != null && hslA != null) {
        parsed = HSLColor.fromAHSL(hslA as double, hslH, hslS, hslL).toColor();
      }
    }
  } else if (_namedColors.containsKey(color)) {
    parsed = Color(_namedColors[color]!);
  }

  if (parsed != null) {
    _cachedParsedColor[color] = parsed;
  }

  return parsed;
}