DEV Community

Cover image for How to use hexadecimal colour strings in Flutter
Mighty
Mighty

Posted on • Edited on • Originally published at mightytechno.com

How to use hexadecimal colour strings in Flutter

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

Top comments (1)

Collapse
 
aboutandre profile image
aboutandre

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; }