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

Time:08-05

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?

CodePudding user response:

An approach of min is inspired by this article an approach is to use the opacity with fixed red, green and blue channels. Color also stored seperately the red, green and blue channels that are accessible according to this Documentation.

Having this 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.

CodePudding user response:

You can check this page, https://gist.github.com/Nitingadhiya/58022151fb8bab45b2734f05bb70d7b3

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

}

var materialColor = getMaterialColor(Color(0xFF42A5F5));


print(materialColor);
  • Related