I have a string in Flutter that represents a color. The string can be:

  • A hexadecimal color code like #FFFFFF or #000000

  • A named color like "white", "black", "red"

I want to convert this string into a Color object.

I know I can maintain a map like:

{'white': '#FFFFFF', 'black': '#000000'}

But this is not feasible because I cannot predict all possible color names.

What I tried:

For hex strings, I wrote this helper:


static Color hex(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll('#', '');
  if (hexColor.length == 6) {
    hexColor = 'FF$hexColor'; // Add alpha if missing
  }
  return Color(int.parse(hexColor, radix: 16));
}

Is there a built-in Flutter/Dart way to handle both cases?

3 Replies 3

There isn't a single built-in Flutter/Dart function to convert a string that could be either a hex code OR a named color into a Color object without maintaining a lookup map for the named colors.

There is a package named color which has a map of color you can use that in your project checkout the list

You can use the flutter_color package and achieve what you'e looking for without maintaining manual color mapping.

How it will solve my problem? I expect to pass the string to a method it may either hex code string or named color string and it should return the color.

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.