toColor method

Color? toColor()

Returns a Color parsed from the contents of the String.

Supports Hex colors with or without a leading #

Implementation

Color? toColor() {
  try {
    var hexColor = toUpperCase().replaceAll('#', ''); // Remove '#' and make uppercase for consistency.

    if (hexColor.length == 3) {
      // Convert shorthand (3 digits) to full length (6 digits)
      hexColor = hexColor.split('').map((c) => '$c$c').join();
    } else if (hexColor.length == 6) {
      // If 6 digits, append 'FF' for alpha at the beginning
      hexColor = 'FF$hexColor';
    } else if (hexColor.length != 8) {
      throw const FormatException('Invalid hex color format');
    }

    return Color(int.parse(hexColor, radix: 16));
  } catch (e) {
    return null;
  }
}