'how to override the toString method of an enum in dart
I'm just wondering if it's possible to override the toString
method in dart
this is what I have:
enum Style{italic, bold, underline}
Style.italic.toString()
// print Style.italic, but I want it to be just italic
Solution 1:[1]
Use .name
extension like MyEnum.value.name
.
enum Style { italic, bold, underline }
void main(List<String> args) {
print(Style.italic.name); // italic
}
Run on dartPad
Solution 2:[2]
It's not currently possible to override methods of enum
s.
Edit: It will be possible from Dart 2.17, where the "enhanced enums" feature is planned to be released (if all goes well).
At that point, you will be able to declare methods on enum
declarations, and override toString
.
So, you'd be able to do:
enum Style {
italic, bold, underline;
@override
String toString() => this.name;
}
to get what you ask for.
The name
getter on enum values was added in Dart 2.15.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yeasin Sheikh |
Solution 2 |