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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

i did but it doesnt change..
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');

1 Comment

i found a short code for this, thanks for answering!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.