1

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 )

4 Answers 4

2

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
     }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I can't change the object coming from DB, do you mean something like ... Text( obj.name ,style: TextStyle( color : nameToColor[ obj.somethimg.color] ) ) ???
thanks this one works... Text( obj.name ,style: TextStyle( color : nameToColor[ obj.somethimg.color] ) )
@Salsabeel You're right, I missed that your example shows the data coming from your db. But you seem to have it figured out. Happy Coding!
2

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']),);

Comments

0

you can put in variable Then you can use it.

Example:

const Color Red=Colors.red;

{
   ...
    name:"any name"
  , something:{
        color:Red
     }
}

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.