I may be missing something obvious, but I'm having trouble passing a variable to a parameter or widget in flutter/dart. For example, let's say I have some variable:
String col = 'red';
and I want to pass this to a color parameter to get the equivalent of
color: Colors.red
The difficult thing is that any way I try to pass the value ends up passing a string (which isn't accepted), including trying to pass just the value of col
directly or trying to build a function that returns Colors.col
.
I think what I need is something like a function like
setColor(String str) {
return Colors.str;
}
but, as you might expect, this returns "The getter 'str' isn't defined for the type 'Colors'." (And similarly for:
setColor(String str) {
return Colors.$str;
}
I know one option is to create a function using a bunch of if's, like
setColor(String str) {
if (str==red) return Colors.red;
if (str==blue) return Colors.blue;
if (str==green) return Colors.green;
etc.
}
but I'd prefer a more elegant option if one is available.
EDIT: It looks like this isn't quite as easy as I'd hoped (see answers and comments to answers below).