Skip to content
DeveloperMemos

Using hex codes for colors in Flutter

Flutter Tips, Flutter, Packages1 min read

The Color class in Flutter is really easy to work with but one of the things that it lacks out of the box is a way to use hex codes to specify Colors. This is a little bit frustrating but I guess it isn't really that uncommon either.

If you search for solutions on Google or DuckDuckGo there are a lot of posts that suggest you just create your own extension to do this. This isn't necessarily a bad solution either, but I prefer personally to use a great package called Supercharged - I wrote a little bit about Supercharged in a previous post.

Installation and usage

Just run flutter pub add supercharged and the Flutter CLI will do all the work for you.

After the package is installed you just need to import(or type 'Supercharged', your IDE should pick it up):

1import 'package:supercharged/supercharged.dart';

And then you can use hex color codes like this:

1"#FFFFFF".toColor();

You can also use it like this too:

1"red".toColor();

Why add another package?

This is a question I actually ask myself a lot. You should really think about whether you need a package or not before you add it because each package you add slowly increases your maintenance burden. I think the value that Supercharged provides outweighs this increase in maintenance burden(it isn't really updated that frequently either). I also think the add to maintenance burden is low because it is a pure Dart package, in my experience that packages that add most to future maintenance are plugins that include native code.

The other point that I will make is that Supercharged isn't just for using hex color codes. It adds in a lot of language features that are missing in Dart/Flutter. It can also do a lot of other things handle user input:

1"2.1".toDouble(); // 2.1
2"42".toInt(); // 42
312.between(0, 30); // true

Or even help you safely access Iterable values:

1[].firstOrNull; // (now supported by Dart collection package)
2[].lastOrNull; // (now supported by Dart collection package)
3
4[].firstOrElse(() => Placeholder()); // Produce default values
5[].lastOrElse(() => Placeholder()); // on the fly

If you want more examples of the benefits that Supercharged can bring to your project make sure to check out its listing on pub.dev.