flutter theme

How to use hexadecimal color strings in Flutter

Using hexadecimal colour string your Flutter app

Flutter natively not supported of setting colours as a hexadecimal string value. Flutter only accept integer value to colour like 0xFFB92B6D.

But It pretty easy to implement a simple method to do convert the hexadecimal string values in a flutter to colour.

Method to convert a hexadecimal string to color

These are the steps need to follow when converting hex string to int colour. This will return the Color object and you can directly assign to anywhere which need to add those colours.

  1. Remove the # value
  2. Add 0xFF to the front of the string if the colour doesn’t have opacity value.
  3. If the colour string has opacity value, discard the FF and append-only 0x.
  4. Convert to Color.
 Color colorConvert(String color) {
        color = color.replaceAll("#", "");
        if (color.length == 6) {
          color = "0xFF" + color;
        } else if (color.length == 8) {
          color = "0x" + color;
        return Color(int.parse(color));

0xFF represent the colour with full opacity. Therefore you need to append that part only if the colour doesn’t have opacity. If the colour string has only 6 characters, that’s mean it does not have opacity value. If the colour string has 8 characters it will have opacity values. In that case, we append only the 0x part to the string.

Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124