I have a string in Flutter that represents a color. The string can be:
A hexadecimal color code like
#FFFFFFor#000000A named color like
"white","black","red"
I want to convert this string into a Color object.
I know I can maintain a map like:
{'white': '#FFFFFF', 'black': '#000000'}
But this is not feasible because I cannot predict all possible color names.
What I tried:
For hex strings, I wrote this helper:
static Color hex(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll('#', '');
if (hexColor.length == 6) {
hexColor = 'FF$hexColor'; // Add alpha if missing
}
return Color(int.parse(hexColor, radix: 16));
}
Is there a built-in Flutter/Dart way to handle both cases?