parseColorHex function

Color parseColorHex(
  1. String? hexString,
  2. Color defaultColor
)

Parses a hexadecimal color string into a Color object. Supports 3-digit and 6-digit hex codes, with or without a leading '#'. Returns defaultColor if parsing fails or the string is null/empty.

Implementation

Color parseColorHex(String? hexString, Color defaultColor) {
  if (hexString == null || hexString.isEmpty) {
    return defaultColor;
  }

  String cleanHex =
      hexString.startsWith('#') ? hexString.substring(1) : hexString;

  // Handle single character "0" or other non-standard small strings by returning default
  if (cleanHex.length < 3) {
    // Optionally log a warning for unexpected format if not "0"
    // debugPrint('Unexpected short hex color string "$hexString", using default.');
    return defaultColor;
  }

  if (cleanHex.length == 3) {
    // Expand 3-digit hex (e.g., "F00" to "FF0000")
    cleanHex = cleanHex.split('').map((char) => char * 2).join();
  }

  if (cleanHex.length == 6) {
    try {
      // Add FF for full opacity (ARGB)
      return Color(int.parse(cleanHex, radix: 16) + 0xFF000000);
    } catch (e) {
      debugPrint('Error parsing hex color "$hexString": $e');
      return defaultColor;
    }
  }
  return defaultColor;
}