DEV Community

Cover image for Custom Swatch for Material App Theme – primarySwatch 
Rohan Joshi
Rohan Joshi

Posted on

Custom Swatch for Material App Theme – primarySwatch 

Error Code

‘Color’ is not a subtype of type ‘MaterialColor?’, ever got this kind of error at runtime, most probably, defining the primarySwatch for your App.

So let’s find out how to define a custom swatch that would work as expected.

A color that has a small table of related colors called a “swatch” — Dart Docs

To create our own small table we need some values to put it in, right. So where can we get them? People on the earth are just awesome, we have a tool Make Tints and Shades to our rescue.

Make Tints and Shades

Get any color HEX code you want paste it in that box, and then click on ‘Make tints and Shade’ (Tip for future — Hover the shades to copy the code)
Create a new dart file for our new values' home. I have named it ‘palette.dart’. (You guys can post your creative names in comments 😜)

From Dart Documentation

const MaterialColor(
int primary,
Map<int, Color> swatch
)
//Creates a color swatch with a variety of shades.
//The primary argument should be the 32 bit ARGB value of one of the values in the swatch, as would be passed to the new Color constructor for that same color, and as is exposed by value. (This is distinct from the specific index of the color in the swatch.)
Enter fullscreen mode Exit fullscreen mode

To tap into the desired value, all you need to create is a Map. That is exactly what we have created below with defining a class Palette for better use and scalability in the future.

Now we just need to import our newly created dart file in main.dart for implementation.

When we define a primarySwatch by ourselves, Theme itself takes some decision in defining colors for widgets like AppBar, FAB, etc. And that’s it, we have a very own customized primarySwatch defined.

Top comments (1)

Collapse
 
heyumid profile image
Umid

what is it?