Reputation: 55
I have a set of data that comes from DB something like this
{
...
name:"any name"
, something:{
color:"red"
}
}
based on this (can't change DB ), How can I display the name in a widget with background color dynamically, "red" for example
( take a color string red converted to Color type )
Upvotes: 1
Views: 1158
Reputation: 55
so thanks to @Tipu Sultan and @Er1.
I tried another solution and it works fine
Map<String, dynamic> objFormDB= {
"name": "any name",
"something": {"color": "red"}
};
Map<String, Color> nameToColor = {
'red' : Colors.red,
'blue' : Colors.blue,
}
and I tried with Text widget
Text( objFormDB.name
,style: TextStyle( color : nameToColor[ objFormDB.somethimg.color] )
)
that's simple :)
Upvotes: 0
Reputation: 1865
Actually there is no such way. But if the value of color is known then we can do something like this
Map<String, dynamic> map = {
"name": "any name",
"something": {"color": "red"}
};
Color getColor(String color) {
switch (color) {
//add more color as your wish
case "red":
return Colors.red;
case "blue":
return Colors.blue;
case "yellow":
return Colors.yellow;
case "orange":
return Colors.orange;
case "green":
return Colors.green;
default:
return Colors.transparent;
}
}
Use this like
Container(color: getColor(map['color']),);
Upvotes: 2
Reputation:
you can put in variable
Then you can use it.
Example:
const Color Red=Colors.red;
{
...
name:"any name"
, something:{
color:Red
}
}
Upvotes: 0
Reputation: 2758
This is not possible as far as I know.
But you could do something like this:
Map<String, Color> nameToColor = {
'red' : Colors.red,
'blue' : Colors.blue,
}
and then
{
...
name:"any name"
, something:{
color: nameToColor['red'] ?? Color.green //or any other default color
}
}
Upvotes: 2