1

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.

sungchan
  • 79
  • 10
  • 3
    Does this answer your question? [How do I use hexadecimal color strings in Flutter?](https://stackoverflow.com/questions/50081213/how-do-i-use-hexadecimal-color-strings-in-flutter) – Lulupointu Oct 11 '20 at 10:30

2 Answers2

2

color : Color(int.parse(bgColor.replaceAll('#', '0x')));

rstrelba
  • 1,838
  • 15
  • 16
0

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');
Lulupointu
  • 3,364
  • 1
  • 12
  • 28