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