可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it. I need to get the value of the enum as a string such as can be done with Java but cannot.
For instance little test code snippet returns 'day.MONDAY' in each case when what I want is 'MONDAY"
enum day {MONDAY, TUESDAY}
print( 'Today is $day.MONDAY');
print( 'Today is $day.MONDAY.toString()');
Am I correct that to get just 'MONDAY' I will need to parse the string?
回答1:
Sadly, you are correct that the toString method returns "day.MONDAY"
, and not the more useful "MONDAY"
.
You can get the rest of the string as:
day theDay = day.MONDAY;
print("${theDay.toString().substring(theDay.toString().indexOf('.')+1)}");
Hardly convenient, admittedly.
If you want to iterate all the values, you can do it using day.values
:
for (day theDay in day.values) {
print(theDay);
}
回答2:
Bit shorter:
String day = theDay.toString().split('.').last;
回答3:
There is a more elegant solution:
enum SomeStatus {
element1,
element2,
element3,
element4,
}
const Map<SomeStatus, String> SomeStatusName = {
SomeStatus.element1: "Element 1",
SomeStatus.element2: "Element 2",
SomeStatus.element3: "Element 3",
SomeStatus.element4: "Element 4",
};
print(SomeStatusName[SomeStatus.element2]) // prints: "Element 2"
回答4:
I use structure like below:
class Strings {
static const angry = "Dammit!";
static const happy = "Yay!";
static const sad = "QQ";
}
回答5:
My approach is not fundamentally different, but might be slightly more convenient in some cases:
enum Day {
monday,
tuesday,
}
String dayToString(Day d) {
return '$d'.split('.').last;
}
In Dart, you cannot customize an enum's toString
method, so I think this helper function workaround is necessary and it's one of the best approaches. If you wanted to be more correct in this case, you could make the first letter of the returned string uppercase.
You could also add a dayFromString
function
Day dayFromString(String s) {
return Day.values.firstWhere((v) => dayToString(v) == s);
}
Example usage:
void main() {
Day today = Day.monday;
print('Today is: ${dayToString(today)}');
Day tomorrow = dayFromString("tuesday");
print(tomorrow is Day);
}
回答6:
I use these two functions to get the name of the enum value and, vise versa, the enum value by the name:
String enumValueToString(Object o) => o.toString().split('.').last;
T enumValueFromString<T>(String key, List<T> values) =>
values.firstWhere((v) => key == enumValueToString(v), orElse: () => null);
Usage examples:
enum Fruits {avocado, banana, orange}
...
final banana = enumValueFromString<Fruits>('banana', Fruits.values);
print(enumValueToString(banana)); // prints: "banana"