How to use hexadecimal colour strings in Flutter
Mighty

Mighty @mightytechno

About: Just an another Developer 😊

Joined:
Jun 25, 2017

How to use hexadecimal colour strings in Flutter

Publish Date: Mar 16 '20
9 1

Flutter natively not supported by setting colors as a hex string value. But we can implement a simple method to do that job.

Method to convert a hexadecimal string to colour

These are the steps need to follow when converting hex string to int colour.

  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) {
              return Color(int.parse("0xFF"+color));
            } else if (color.length == 8) {
              return Color(int.parse("0x"+color));
            }
          }
Enter fullscreen mode Exit fullscreen mode

hexadecimal colour strings in Flutter

Originally published at mightytechno

Connect with me - Instagram |Blog |Twitter

Comments 1 total

  • aboutandre
    aboutandreApr 17, 2020

    Hey @mightytechno ,
    I am just learning Flutter. So maybe this is not so good.
    But Android Studio was complaining that there was no return value:

    • info: This function has a return type of 'Color', but doesn't end with a return statement.

    So I wrote like this:

    Color colorConvert(String color) {
      color = color.replaceAll("#", "");
      var converted;
      if (color.length == 6) {
        converted = Color(int.parse("0xFF" + color));
      } else if (color.length == 8) {
        converted = Color(int.parse("0x" + color));
      }
      return converted;
    }
    
Add comment