Flutter convert Color to hex string

This is what I'm using:

extension ColorX on Color {
  String toHexTriplet() => '#${(value & 0xFFFFFF).toRadixString(16).padLeft(6, '0').toUpperCase()}';
}

Sample outputs: #00FFFF or #FF69B4

This code also makes sure that alpha is omitted (@bakua's comment)

Some Flutter source code inspiration: util.dart, painting.dart


You can add an extension to Color class to get HexString from the Color object itself directly.

extension HexColor on Color {
  /// 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')}';
}
Color color = Colors.blue ; 
print(color.toHex());

You can convert the value property (includes alpha) or the individual red, green, and blue properties to Hex using int.toRadixString(16):

 var myColor = Colors.blue;
 var hex = '#${myColor.value.toRadixString(16)}';

Tags:

Dart

Flutter