I’m trying to change color of Decoration in ListView builder from static List Map values,
failed with _castError (type ‘String’ is not a subtype of type ‘Color’ in type cast).
What is the correct way to pass color values as Map in Dart with other types of data?
Map:
static const List<Map<String, String>> labels = [
{
'label': 'Water',
'image': 'assets/images/ic_water.png',
'colors': 'Color.fromARGB(255, 100, 216, 221)' tried //255, 100, 216, 221
},
{
'label': 'Food',
'image': 'assets/images/ic_food.png',
'colors': 'Color.fromARGB(255, 100, 216, 221)'
},];
Placement:
ListView.builder(
....
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
color: ConstantValues.labels[i]['colors']! as Color),
..
)```
2
Answers
The code coming from labels[i][‘colors’] is of type
String
. It looks like this:'Color.fromARGB(255, 100, 216, 221)'
. This code is not evaluated, it’s just an array of characters. You will need to try and find a different way to store your color. For example, use hexadecimal representation.Still, the colors are still represented as type
String
, notint
as theColor
class expects: https://api.flutter.dev/flutter/dart-ui/Color-class.htmlYou will need to make your code convert the string to a Color class, not just by using
as
.Where the
fromHex
function can be used from the following answer in SO: How do I use hexadecimal color strings in Flutter?This is not working because your are parsing
string
type in color property which needColor
type.I suggest you should use hex value in map:
Converting Hexcode to Color
special thanks to jossef
you can convert
hexcolor
code toColor
type:Usage:
You can use this in container like this,