hexToColor static method

Color? hexToColor(
  1. String? hexString
)

Implementation

static Color? hexToColor(String? hexString) {
  if (hexString == null || hexString.trim().isEmpty) {
    return null;
  }
  hexString = hexString.replaceAll('#', '').toUpperCase();
  if (hexString.length == 6) {
    // RGB → ARGB,默认不透明
    hexString = 'FF$hexString';
  } else if (hexString.length == 8) {
    // RGBA → ARGB(A在最后,转到前面)
    hexString = hexString.substring(6, 8) + hexString.substring(0, 6);
  } else {
    return null; // 格式不正确
  }

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