Unfortunately, the Color
class constructor in Flutter does not accept a simple hexadecimal string (like #bfeb91
in CSS).
Instead it requires an integer like 0xFFBFEB91
.
So how do we convert an hex string to an integer?
Give this function a hex string and it will return you a Color
!
Color _getColorFromHex(String hexColor) {
hexColor = hexColor.replaceAll("#", "");
if (hexColor.length == 6) {
hexColor = "FF" + hexColor;
}
if (hexColor.length == 8) {
return Color(int.parse("0x$hexColor"));
}
}
It takes a 6 (no alpha channel) or 8 (with alpha channel) character string, with or without the #
prefix.
So what is this FF
business all about?
0xFF
is the hexadecimal notation of the integer 255, which corresponds to 100% opacity in the alpha channel!
By default, Dart creates colors with 0% opacity (i.e. transparent) which is the exact opposite of CSS (and very strange!)
For example, Color(0xBFEB91)
will yield an invisible color as it’s not prefixed with FF
.
Leveraging the power of Dart extensions we can augment String
with a function that returns a Color
:
extension ColorExtension on String {
toColor() {
var hexColor = this.replaceAll("#", "");
if (hexColor.length == 6) {
hexColor = "FF" + hexColor;
}
if (hexColor.length == 8) {
return Color(int.parse("0x$hexColor"));
}
}
}
(or make it a separate utility class!)
Click “Run” and see it in action: