Making Colors from Hex Strings
When you're building a Flutter app, you often get color codes as text, like "#FF0000" for red. But Flutter uses Color
objects, not text strings, for colors. You need a way to change that text string into a Color
that Flutter understands.
This little piece of code helps you do just that in a clean way.
The HexColor Extension
By using an 'extension', we can add a new function directly to the Color
type. This makes it super easy to use later.
The extension is called HexColor
and it works 'on Color'.
How the Code Works
Inside the HexColor
extension, we have a special function called fromHex
. It takes your hexadecimal color string (like "#RRGGBB" or "RRGGBB") as input.
extension HexColor on Color {
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));
}
}
Steps Explained
- It first checks if your string is 6 or 7 characters long (like "RRGGBB" or "#RRGGBB").
- If it is, it adds 'ff' to the start of a temporary text builder. This 'ff' means the color is fully opaque (not transparent).
- It removes any '#' symbol from the start of your hex string.
- It adds the rest of your hex string (RRGGBB) to the temporary text builder.
- Finally, it takes the complete string (which now looks like "ffRRGGBB"), turns it into a number that represents the color, and creates a Flutter
Color
object from it.
Why This Is Useful
Instead of writing complicated code every time you need to convert a hex string, you can just use this extension. It makes your code cleaner and easier to read.