hexToColor method

Color hexToColor()

Converts a hex string to a Color.

Supports #RRGGBB or #AARRGGBB. Returns Colors.transparent if invalid.

Implementation

Color hexToColor() {
  final value = this;
  if (value == null) {
    return Colors.transparent;
  }

  var hexString = value.replaceFirst('#', '').toLowerCase();

  if (hexString.length != 6 && hexString.length != 8) {
    return Colors.transparent;
  }
  if (!RegExp(r'^[0-9a-f]+$').hasMatch(hexString)) {
    return Colors.transparent;
  }

  if (hexString.length == 6) {
    hexString = 'ff$hexString'; // default alpha
  }

  try {
    return Color(int.parse('0x$hexString'));
  } catch (_) {
    return Colors.transparent;
  }
}