Colour.fromHex constructor

Colour.fromHex({
  1. required String hexString,
})

Parses a hex colour string, with or without a leading #.

Accepts RGB, ARGB, RRGGBB and AARRGGBB. Short forms are expanded by doubling each digit, and forms without alpha are made opaque. Throws if the string isn't valid hex.

Colour.fromHex(hexString: '#F80');      // opaque orange
Colour.fromHex(hexString: '80FF8800'); // half-transparent orange

Implementation

factory Colour.fromHex({required String hexString}) {
  String hex = hexString.replaceAll('#', '').toUpperCase();

  if (hex.length == 6) {
    hex = 'FF$hex';
  } else if (hex.length == 3) {
    hex = 'FF${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}';
  } else if (hex.length == 4) {
    hex =
        '${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}';
  }

  return Colour.fromARGB(
    alpha: int.parse(Radix.getDecimal(hex.substring(0, 2), 16)),
    red: int.parse(Radix.getDecimal(hex.substring(2, 4), 16)),
    green: int.parse(Radix.getDecimal(hex.substring(4, 6), 16)),
    blue: int.parse(Radix.getDecimal(hex.substring(6, 8), 16)),
  );
}