flutterdartcolors

How I can convert a Color into MaterialColor so I can have a limited Pallete of colors in my App?


For my application I wanted to limit my palette of colors therefore I made a class full of constants containing instances of Colors:


class Colors 
{
  static var red = Color(0xFFFF1212);
  static var blue = Color(0xFF1212FF);
  static var green = Color(0xFF12F1FA);
}

But sometimes a MaterialColor is required. So somehow I need to convert a Color instance into a MaterialColor instance. But the constuctor requires to offer a swatch (some sort of pallete for it). How I can do this?


Solution

  • An approach of mine is inspired by this article. The way I do it, is to use various opacity channels, with fixed values at red, green and blue channels. Color also is stored in seperate red, green and blue channels that are accessible via instance variables, according to this Documentation.

    Having these pieces of puzzle I made this function:

     MaterialColor getMaterialColor(Color color) {
        final int red = color.red;
        final int green = color.green;
        final int blue = color.blue;
    
        final Map<int, Color> shades = {
          50: Color.fromRGBO(red, green, blue, .1),
          100: Color.fromRGBO(red, green, blue, .2),
          200: Color.fromRGBO(red, green, blue, .3),
          300: Color.fromRGBO(red, green, blue, .4),
          400: Color.fromRGBO(red, green, blue, .5),
          500: Color.fromRGBO(red, green, blue, .6),
          600: Color.fromRGBO(red, green, blue, .7),
          700: Color.fromRGBO(red, green, blue, .8),
          800: Color.fromRGBO(red, green, blue, .9),
          900: Color.fromRGBO(red, green, blue, 1),
        };
    
        return MaterialColor(color.value, shades);
      }
    

    With the code above I perform the following:

    1. I extract the Red Green and Blue channels
    2. I place an opacity for a fixed shades
    3. I use the manufactured shades and place them into MaterialColor

    I know I could use a second parameter with the number of shades but it was too much hassle for me. In my case having some sort of fixed shades is good enough.