How to use hexadecimal color strings in Flutter

October 09, 2022 No comments string flutter dart colors hex

Introduction

In Flutter, we may wish to use hexadecimal color strings. In this post, we'll look at how to do it.

How to use hexadecimal color strings in Flutter

To use hexadecimal color strings in Flutter we need to:

  • convert string to an integer since the Color class in Flutter accepts only int values,
  • we need to set the opacity (255 value is a full opacity represented by the hexadecimal value FF).

The method to convert color in the string to the Color class in Flutter looks as follows:

static Color fromHex(String hexString) {
  final buffer = StringBuffer();
  if (hexString.length == 6 || hexString.length == 7) buffer.write('FF');
  buffer.write(hexString.replaceFirst('#', ''));
  return Color(int.parse(buffer.toString(), radix: 16));
}

or

static int getColorFromHex(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF" + hexColor;
  }
  return int.parse(hexColor, radix: 16);
}

The FF in line hexColor = "FF" + hexColor; sets the opacity to 100%;

Opacity values in hexadecimal:

100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00

The method that takes the opacity also could look like this:

static int getColorFromHex(String hexColor, String opacity) {
  hexColor = hexColor.toUpperCase().replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = opacity + hexColor;
  }
  return int.parse(hexColor, radix: 16);
}

Conclusion

In this article, we learned how to use convert hexadecimal color in strings to the Color class in Flutter.

{{ message }}

{{ 'Comments are closed.' | trans }}