fromHex static method

Color fromHex(
  1. String hexString
)

Safely creates a Color from a hex string.

Edge Cases Handled:

  • Removes '#' and extra whitespace.
  • Converts shorthand hex (e.g., #FFF) to 8-digit format.
  • Error Handling: Returns Colors.black if parsing fails.

Implementation

static Color fromHex(String hexString) {
  try {
    String cleanHex = hexString.replaceAll('#', '').trim();

    if (cleanHex.length == 3) {
      cleanHex = cleanHex.split('').map((c) => '$c$c').join();
    }

    final buffer = StringBuffer();
    if (cleanHex.length == 6) buffer.write('FF');
    buffer.write(cleanHex);

    return Color(int.parse(buffer.toString(), radix: 16));
  } catch (e) {
    debugPrint(
      '[ChromaKitColorUtils] fromHex Error: "$hexString" is not valid. Returning black.',
    );
    return Colors.black;
  }
}