Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Convert RGB values to hex int

In Flutter, I want to put an RGB color as the int primary in a MaterialColor() constructor. How can I convert RGB values into a hex int formatted as such: 0xff------? Sorry for the short question, I really couldn't find it anywhere!

like image 711
Riley Fitzpatrick Avatar asked Jan 28 '26 19:01

Riley Fitzpatrick


1 Answers

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)); 
like image 93
Son of Stackoverflow Avatar answered Jan 31 '26 17:01

Son of Stackoverflow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!