parseColor static method
Parses #RGB, #RRGGBB, #AARRGGBB, rgb(r,g,b) and rgba(r,g,b,a).
Returns null when the value is missing or unparseable.
Implementation
static Color? parseColor(Object? raw) {
if (raw == null) return null;
if (raw is Color) return raw;
if (raw is int) return Color(raw);
var s = raw.toString().trim().toLowerCase();
if (s.isEmpty) return null;
if (s.startsWith('rgb')) {
final nums = RegExp(
r'[\d.]+',
).allMatches(s).map((m) => double.tryParse(m.group(0)!) ?? 0).toList();
if (nums.length >= 3) {
final a = nums.length > 3 ? (nums[3] * 255).round() : 255;
return Color.fromARGB(
a.clamp(0, 255),
nums[0].round().clamp(0, 255),
nums[1].round().clamp(0, 255),
nums[2].round().clamp(0, 255),
);
}
return null;
}
s = s.replaceFirst('#', '').replaceFirst('0x', '');
if (s.length == 3) {
s = s.split('').map((c) => '$c$c').join();
}
if (s.length == 6) s = 'ff$s';
if (s.length != 8) return null;
final v = int.tryParse(s, radix: 16);
return v == null ? null : Color(v);
}