Flutter: Convert RGB values to hex int Flutter: Convert RGB values to hex int dart dart

Flutter: Convert RGB values to hex int


You can use the below function to convert RGB to Hex,

int hexOfRGBA(int r,int g,int b,{double opacity=1})     {           r = (r<0)?-r:r;          g = (g<0)?-g:g;          b = (b<0)?-b:b;          opacity = (opacity<0)?-opacity:opacity;          opacity = (opacity>1)?255:opacity*255;          r = (r>255)?255:r;          g = (g>255)?255:g;          b = (b>255)?255:b;          int a = opacity.toInt();          return int.parse('0x${a.toRadixString(16)}${r.toRadixString(16)}${g.toRadixString(16)}${b.toRadixString(16)}');    }

Usage:

    Color(hexOfRGBA(0,0,0,opacity: 0.7)); 

However for some reason if you want to keep your use-case specific,

You can use the below function to convert RGB to Hex (without transparency),

int hexOfRGB(int r,int g,int b)     {       r = (r<0)?-r:r;      g = (g<0)?-g:g;      b = (b<0)?-b:b;      r = (r>255)?255:r;      g = (g>255)?255:g;      b = (b>255)?255:b;      return int.parse('0xff${r.toRadixString(16)}${g.toRadixString(16)}${b.toRadixString(16)}');    }

Usage:

Color(hexOfRGB(255,255,255)); 

If you want to compulsorily include transparency (i.e. RGBA),

   int hexOfRGBA(int r,int g,int b,double opacity)         {          r = (r<0)?-r:r;          g = (g<0)?-g:g;          b = (b<0)?-b:b;          opacity = (opacity<0)?-opacity:opacity;          opacity = (opacity>1)?255:opacity*255;          r = (r>255)?255:r;          g = (g>255)?255:g;          b = (b>255)?255:b;          int a = opacity.toInt();          return int.parse('0x${a.toRadixString(16)}${r.toRadixString(16)}${g.toRadixString(16)}${b.toRadixString(16)}');        }

Usage:

Color(hexOfRGBA(0,0,0,0.7)); 


In Flutter the Color class only accepts integers as parameters, or there is the possibility to use the named constructors fromARGB and fromRGBO.

So we only need to convert the string #b74093 to an integer value. Also we need to respect that opacity always needs to be specified.255 (full) opacity is represented by the hexadecimal value FF. This already leaves us with 0xFF. Now, we just need to append our color string like this:

final color = const Color(0xffb74093);

The letters can by choice be capitalized or not:

final color = const Color(0xFFB74093);