Search code examples
dartflutter

Flutter convert Color to hex string


How can I convert a flutter Color class instance into a hex string?

For example, I would like to convert Colors.blue to what would be '#4286f4'.

Usecase is letting the user choose a color and save it in the database as a hex color.

I have checked related questions and they are for converting the other way around.


Solution

  • 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());