parseCssColor function

Color? parseCssColor(
  1. dynamic rawColor
)

Parses CSS-style hex colors (#RGB, #RRGGBB, #RRGGBBAA, transparent) into Flutter Color.

Implementation

Color? parseCssColor(dynamic rawColor) {
  if (rawColor == null) return null;
  final str = rawColor.toString().trim().toLowerCase();
  if (str == 'transparent') return const Color(0x00000000);
  if (!str.startsWith('#')) return null;

  final hex = str.substring(1);
  if (hex.length == 3) {
    // #RGB -> #RRGGBB
    final r = hex[0];
    final g = hex[1];
    final b = hex[2];
    return Color(int.parse('FF$r$r$g$g$b$b', radix: 16));
  } else if (hex.length == 6) {
    // #RRGGBB
    return Color(int.parse('FF$hex', radix: 16));
  } else if (hex.length == 8) {
    // #RRGGBBAA -> Flutter Color(0xAARRGGBB)
    final rr = hex.substring(0, 2);
    final gg = hex.substring(2, 4);
    final bb = hex.substring(4, 6);
    final aa = hex.substring(6, 8);
    return Color(int.parse('$aa$rr$gg$bb', radix: 16));
  }
  return null;
}