Home > Software design >  String is not a subtype of Color
String is not a subtype of Color

Time:09-04

I have a picture on the page and below it a color pallette of 9 colors. When user clicks a color from the pallette, the image is to show that color on it. For that I want to use an array and I am changing a variable on tap

selectedIndex = 0  ->  8;

And I want to pass the color in ColorFilter

 child: ColorFiltered(
                colorFilter: ColorFilter.mode(
                    Color(filters[selectedIndex]),
                    BlendMode.color),
                child: Image('')),

I am getting an error. String is not subtype of Color. How can I do this?

This is my filters array

   "Colors.black",
   "Colors.blue",
   "Colors.yellow",
   "Colors.orange",
   "Colors.pink",
   "Colors.green",
   "Colors.white",
   "Colors.indigo",
   "Colors.grey",
   "Colors.red",
 ];

CodePudding user response:

It expects a Color type, not a String. Remove the quotes

[
Colors.black,
Colors.blue,
Colors.yellow,
etc..
];

CodePudding user response:

Your filters array is a List<String>, but you are not providing any information about the expected color.

You have two ways to solve this problem:

1 - Convert your List<String> to a List<Color>

2 - Change the values of your List<String> to hexadecimal codes. (I would recommend you to change your List<String> to a List<int>)

Example: In the first way, your filters array should looks something like:

final List<Color> filters = [
   Colors.black,
   Colors.blue,
   Colors.yellow,
   Colors.orange,
   Colors.pink,
   Colors.green,
   Colors.white,
   Colors.indigo,
   Colors.grey,
   Colors.red,
];

// ColorFilter
ColorFilter.mode(filters[selectedIndex], BlendMode.color);

If you want to keep your array as a List<Int> then you will need to provide the hexadecimal code of the expected color, like:

final List<Int> filters = [
   0xFF000000,
   0xFF0000FF,
   0xFFFF0000,
];

// ColorFilter
ColorFilter.mode(Color(filters[selectedIndex]), BlendMode.color);
  • Related