-1

In my app, I have buttons which have the names of colours. When the user presses the button, the name of the colour is recorded as a string and then passed to my result screen widget. Temporarily, I'm using a getter which does this:

  Color get resultColor {
    Color faveColorTDT;
    
    if (faveColor == 'Black') {
      faveColorTDT = Colors.black;
    }
    else if (faveColor == 'Red') {
      faveColorTDT = Colors.red;
    }
    else if (faveColor == 'Brown') {
      faveColorTDT = Colors.brown;
    }
    else {
      faveColorTDT = Colors.blue;
    }

    return faveColorTDT;
  }

and then I use the getter in the Text widget like this:

style:
  TextStyle(color: resultColor)

However, this is pretty inefficient if the number of colours increases. So is there a way to convert a String to a Color or use a string in the colour parameter?

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52

1 Answers1

1

It's not possible since color names are just abstract words to refer to the actual hexadecimal code representation in digital. You won't get it, at least not without a solution longer than it needs to be.

You could take another an approach less painful tough. Put your colors(Colors.black, Colors.blue, etc.) to be sent by those buttons you said, so that when the buttons are pressed, they'll send the colors objects rather than the color strings. This way you avoid the conditionals.

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52