In Flutter, you can use included the Color
class to create a color from a hexadecimal color string value. The Color
class accepts a 32 bit integer value with the first 8 bits denoting the alpha channel (transparency) and the subsequent 24 bits representing the red, green and blue channels.
To create a color object from a hexadecimal value, you can simply pass the hex value to the Color()
constructor. For instance if you want the color red you can utilize this code snippet;
Color color = Color(0xFFFF0000);
To form a color using a string, start by converting the string into a 32 bit integer. Here’s an example of how it can be done;
String hexColor = "#FF0000"; // red color
Color color = Color(int.parse(hexColor.substring(1, 7), radix: 16) + 0xFF000000);
In the code above, the substring(1, 7)
method removes the character “#” from the color string. The int.parse()
method then converts the remaining string into a 32-bit integer value using the radix
argument. This specifies that the string is in base 16 (hexadecimal). The + 0xFF000000
part adds the alpha channel value of 255 (fully opaque) to the color value, because our initial color string does not contain an alpha channel.
Colors with Transparency
You can also make colors with transparency by using an eight digit hexadecimal color code. The initial two digits indicate the alpha channel, which manages the opacity of the color. For example, to create a semi-transparent red color, you can use:
Color semiTransparentColor = Color(0x80FF0000);
Or for a given string value:
String hexColor = "#FF0000"; // red color
Color semiTransparentColor = Color(int.parse(hexColor.substring(1, 7), radix: 16) + 0x80000000);
The output 0x80FF0000
is the hexadecimal color value for red with 50% transparency. The first two digits “80” represent the alpha channel, and the remaining six digits represent the color components.
Usage in Widgets
You can now simply use the color
object to set the color of any widget in your Flutter application:
Container(
color: color,
child: ...
)
You can also use the color object as a parameter in some widgets, such as the IconButton
widget:
IconButton(
icon: Icon(Icons.add),
color: color,
onPressed: () {},
)
Foto von Ramakant Sharda auf Unsplash
Leave a Reply