Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter/Dart: Convert HEX color string to Color?

Our database has colors saved as a String like "#AABBCC" and so I'm basically looking for a function like this: Color.parseColor("#AABBCC"); for Flutter

The Color class requires something like this Color(0xFF42A5F5) so I need to convert "#AABBCC" to 0xFFAABBCC

like image 620
Jus10 Avatar asked May 17 '18 01:05

Jus10


People also ask

How do you convert hex color to color in Flutter?

Create a variable of type Color and assign the following values to it. Color myHexColor = Color(0xff123456) // Here you notice I use the 0xff and that is the opacity or transparency // of the color and you can also change these values. Use myHexColor and you are ready to go.

How do you change a String color to color in Flutter?

You can retrieve color value and change it back to color like this : int value = int. parse(_storeColorValue); Color color = Color(value).

How do you parse colors in Flutter?

Instead, you can parse the string into a value and construct a new Color object. Color color = new Color(0x12345678); String colorString = color. toString(); // Color(0x12345678) String valueString = colorString. split('(0x')[1].

How do you pass RGB color in Flutter?

If you want to specify opacity as a double value between 0.0 (transparent) and 1.0 (fully opaque), use Color. fromRGBO() . The opacity value is the last parameter. But if you want to specify opacity as an integer value between 0 (transparent) and 255 (fully opaque), use Color.


2 Answers

/// Construct a color from a hex code string, of the format #RRGGBB. Color hexToColor(String code) {   return new Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000); } 
like image 200
Richard Heap Avatar answered Sep 17 '22 11:09

Richard Heap


I'm using this function in my project which handles converting the hex string to a Color.

Color hexToColor(String hexString, {String alphaChannel = 'FF'}) {   return Color(int.parse(hexString.replaceFirst('#', '0x$alphaChannel'))); } 

The idea here is that now you can pass this function a hex string which is something like this '#ffffff' in addition to that you can pass an alpha channel. What alpha channel does is it handles the opacity of your color and you can pass it to Color directly.

About alpha channels the FF part is a hex representation of 0-100 is like:

0 = 00 1 = 03 2 = 05 ... 9 = 17 ... 10 = 1A 11 = 1C 12 = 1F ... 99 = FC 100 = FF

Let's assume you want to convert #000000 into a Color and have a 0.1 opacity on it. You can simply call this function like this:

hexToColor('#000000', alphaChannel: '1A'); 

And if you just call it like this:

hexToColor('#000000'); 

Then it will only return you a black color with 1 opacity. Hope this will help to anyone wondering how to handle opacity and color handling a bit more further.

like image 35
Mertcan Diken Avatar answered Sep 20 '22 11:09

Mertcan Diken