toColorShortMaybeNull method
Convert a HEX value encoded (A)RGB string to a Dart Color.
- The string may include the '#' char, but does not have to.
- String may also include '0x' Dart Hex indicator, but does not have to.
- Any '#' '0x' patterns are trimmed out and String is assumed to be Hex.
- The String may start with alpha channel hex value, but does not have to, if alpha value is missing "FF" is used for alpha.
- String may be longer than 8 chars, after trimming out # and 0x, it will be RIGHT truncated to max 8 chars before parsing.
- If
enableShortRGB
is true a CSS style 3 char RGB value is interpreted as RRGGBB, if false it used it as a partial color value.
IF the resulting string cannot be parsed to a Color, is empty or null THEN NULL is returned ELSE the Color is returned.
Implementation
Color? toColorShortMaybeNull(bool enableShortRGB) {
// If String was null or zero length, then we return null, cannot parse.
if (this == null || this == '') return null;
// If String length is > 200 we as a safety precaution will not try to
// parse it to a color, for shorter lengths the last 8 chars will be used.
if ((this?.length ?? 200) > 200) return null;
// Remove all num signs, we allow them, but disregard them all.
String hexColor = this?.replaceAll('#', '') ?? '';
if (hexColor == '') return null;
// Remove all spaces, we allow them, but disregard them all.
hexColor = hexColor.replaceAll(' ', '');
if (hexColor == '') return null;
// Remove all '0x' Hex code marks, we allow them, but disregard them all.
hexColor = hexColor.replaceAll('0x', '');
if (hexColor == '') return null;
// If the input is exactly 3 chars long, we may have a short Web hex code,
// let's make the potential 'RGB' code to a 'RRGGBB' code.
if (hexColor.length == 3 && enableShortRGB) {
hexColor = hexColor[0] +
hexColor[0] +
hexColor[1] +
hexColor[1] +
hexColor[2] +
hexColor[2];
}
// Pad anything shorter than 7 with left 0 -> fill non spec channels with 0.
hexColor = hexColor.padLeft(6, '0');
// Pad anything shorter than 9 with left F -> fill with opaque alpha.
hexColor = hexColor.padLeft(8, 'F');
// We only try to parse the last 8 chars in the remaining string, rest can
// still be whatever.
final int length = hexColor.length;
final int? intColor =
int.tryParse('0x${hexColor.substring(length - 8, length)}');
return intColor != null ? Color(intColor) : null;
}