Header

In Flutter, the Color class can be constructed in a few different ways.

The simplest one is to use an integer value in relevant constructor.

const Color(0xFF42A5F5)

The other simpler way maybe, to create color is from `RGB related constructors:

Color c2 = const Color.fromARGB(0xFF, 0x42, 0xA5, 0xF5);
Color c3 = const Color.fromARGB(255, 66, 165, 245);
Color c4 = const Color.fromRGBO(66, 165, 245, 1.0);

Notice that the values can be expressed in any form as long as it is integer.

Usually the problem is that we want to create color from a hexadecimal string in flutter. In such a cases, we need to convert the string to a string.

One thing to remember that for the int constructor, we have to have the opacity ( FF by default ), in front.

If you want to do this dynamically in your program, the best way to achieve this is to use an (extension method)[https://dart.dev/language/extension-methods] on the color class. The extension method would be

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')}';
}

Then you can use it like

void main() {
  final Color color = HexColor.fromHex('#aabbcc');

  print(color.toHex());
  print(const Color(0xffaabbcc).toHex());
}