colorFromHex function

Color? colorFromHex(
  1. String inputString, {
  2. bool enableAlpha = true,
})

Parses a hex colour string into a Flutter Color, or returns null if the string is invalid.

Supports 3-digit (#F00), 6-digit (#FF0000), and 8-digit (#FFFF0000) hex strings, with or without the leading #.

Set enableAlpha to false to force full opacity regardless of any alpha component in the input.

Implementation

Color? colorFromHex(String inputString, {bool enableAlpha = true}) {
  final RegExp hexValidator = RegExp(kCompleteValidHexPattern);
  if (!hexValidator.hasMatch(inputString)) return null;
  String hexToParse = inputString.replaceFirst('#', '').toUpperCase();
  if (!enableAlpha && hexToParse.length == 8) {
    hexToParse = 'FF${hexToParse.substring(2)}';
  }
  if (hexToParse.length == 3) {
    hexToParse = hexToParse.split('').expand((i) => [i * 2]).join();
  }
  if (hexToParse.length == 6) hexToParse = 'FF$hexToParse';
  final intColorValue = int.tryParse(hexToParse, radix: 16);
  if (intColorValue == null) return null;
  final color = Color(intColorValue);
  return enableAlpha ? color : color.withAlpha(255);
}