I have a dynamic variable which will initiate by some colors
String bgColor = "#f8d547";
and I want to set this color property from that variable
decoration: BoxDecoration(
color: bgColor,
),
how can I achieve that? Thank you.
I have a dynamic variable which will initiate by some colors
String bgColor = "#f8d547";
and I want to set this color property from that variable
decoration: BoxDecoration(
color: bgColor,
),
how can I achieve that? Thank you.
Duplicate of How do I use hexadecimal color strings in Flutter?
Please go there to have the detailed answer, anyway here is the bit which you want.
You have to create a new function, which can be created as an extension of Color:
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')}';
}
To use it:
final Color color = HexColor.fromHex('#aabbcc');