In Flutter, the Color classColor class only accepts integers as parametersintegers as parameters, or there is the possibility to use the named constructors fromARGB and fromRGBO.
So we only need to convert the string #b74093 to an integer value. Also we need to respect that opacityopacity always needs to be specified.
255 (full) opacity is represented by the hexadecimal value FF. This already leaves us with 0xFF0xFF. Now, we just need to append our color string like this:
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 ? '#' : ''}'
'${a̶l̶p̶h̶a̶alpha.toRadixString(16).padLeft(2, '0')}'
'${r̶e̶d̶red.toRadixString(16).padLeft(2, '0')}'
'${̶g̶r̶e̶e̶n̶green.toRadixString(16).padLeft(2, '0')}'
'${̶b̶l̶u̶e̶blue.toRadixString(16).padLeft(2, '0')}';
}
NOTE: After version 3.27 of flutterFlutter, the properties alpha, red, green, and blue are now deprecated. Check the changes on breaking-changes.