extension HexColor on Color {
/// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
static Color fromHex(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
'${alpha.toRadixString(16).padLeft(2, '0')}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}';
}
///
/// Convert a color hex-string to a Color object.
///
Color getColorFromHex(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll('#', '');
if (hexColor.length == 6) {
hexColor = 'FF' + hexColor;
}
return Color(int.parse(hexColor, radix: 16));
}
Color myHexColor = Color(0xff123456)
// Here you notice I use the 0xff and that is the opacity or transparency
// of the color and you can also change these values.
Color colorFromHex(String hexColor) {
final hexCode = hexColor.replaceAll('#', '');
if (hexColor.length == 6) {
hexColor = 'FF' + hexColor; // FF as the opacity value if you don't add it.
}
return Color(int.parse('FF$hexCode', radix: 16));
}