How to Use Tailwind Colors in your Flutter apps


As I’ve said before, I’m a big fan of both Flutter and TailwindCSS.

One thing in particular that I missed from Tailwind while developing for Flutter is an access to the Color Palette because:

  • The default Material Palette, while nice does not easily play well with matching different colors.
  • I make extensive use of greys, which are sadly lacking in Material.

So today we’ll see how to get this palette and make it available in Flutter.

Finding the colors

Going through the TailwindCSS github gives us the default config over here. Which is a pretty simple JSON file all things considered.

Now that we know what we’re coming from, let’s see how to turn this into usable dart code.

I usually develop for Android so I’ll stick with the Material Color implementation as a target. This way we’ll be able to use the Tailwind colors the same way we would use Material colors.

Taking at look at the Flutter github tells us everything we need to know: our implementation will need to extend ColorSwatch and provide shade indexes like so:

 gist MBeliou e73e2b9d43835de0439ec9266356a89f  

We’ll just need one last piece of code:

Since TailwindCSS colors are defined as Hex, we’ll need to convert them to a Color Flutter class. We’ll just use the extension method from this StackOverflow Post’s accepted answer.

We’ll also want to namespace our newly made colorspace just like the MaterialColor “Colors”, we’ll be choosing “TWColors”.

Here’s the complete code to convert a json containing only the Tailwind colors.

<!-- {{< gist MBeliou be358b9c68035f6061681010c49b448c "main.dart" >}} -->

We’ll just to call the script like so:

dart main.dart >> myTWColors.dart

For those who don’t know, the >> will eat our output and send it inside the myTWColors.dart file.

Don’t forget to put these generated classes inside a TWColors class and you’re mostly done.

Bonus Points

This script can also be used to parse any Tailwind custom colors definition. You can try it out with the TailwindUI (A components set made with TailwindCSS and an improved Color Palette meant to promote easy color swapping) which can be found over here.

Check it out: I’ve also made a flutter package that works straight out the box for every Flutter target!