Flutter: Creating custom color swatch for MaterialColor

Why there’s no built-in method that converts a hex value into a MaterialColor variable, we’ll never know

Nicholas Song
3 min readMay 23, 2019
A screenshot of Material Design Colors

Although Flutter is definitely an excellent choice of framework when it comes to cross-platform mobile & web developments, its capability for color manipulation is actually far from greatness.

When we create a brand new Flutter project by running $ flutter create myapp on Terminal, the very first and the easiest customization we can try out should be modifying the color theme of the application… right? No!

Want to read this story later? Save it in Journal.

Color theming of the application in the new project

The primarySwatch parameter which is responsible for painting major parts of the application (top navigation bar as the most typical example) which adheres Material Design paradigm — never accepts variables other than MaterialColor type. That’s quite messed up because we all know what kind of color variety Google’s Material Concept can possibly provide us: the same old lazy, dull, pre-defined colors like amber, indigo, limeBlue, deepPurple, and transparent!

Assigning my favorite color values (e.g. #174378) into this named parameter using one or two lines of Flutter’s built-in methods is next to impossible if it is possible at all. We absolutely need a utility method that generates custom MaterialColor objects from the hex integer like above. Hence this trick.

As a prior notice: what I am going to do directly credits the constructor of MaterialColor. We can’t use it as is but we can’t avoid it either :)

MaterialColor(int primary, Map<int, Color> swatch)

In a nutshell, given the right color value (which we already have) and a swatch of different shades, we can make it happen, just like that!

This code is pretty much self-explanatory. The different shade values of the swatch should gradually spread out. The threshold of 0.5 in Line #10 is important because the actual color represented by a new MaterialColor object should be identical to its own shade500.

Now you should be able to use it as here.

primarySwatch: createMaterialColor(Color(0xFF174378))

And voila! We got it working. But what does this return value exactly look like? It’s basically the same thing as below, but is something collected without any manual calculation which appears so annoying to our big minds :)

You might don’t want to do this manually.

Thanks for reading!

My name is Nicholas Song, a front-end web developer who can also be found on LinkedIn, GitHub, and Stackoverflow. Did you like my article? Then destroy 👏 button by long-pressing it! It will definitely motivate me to write more about Flutter. 😎

--

--

Nicholas Song

Professional Web Developer, an ardent supporter of functional approaches