Ndimah
Ndimah

Reputation: 189

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

Upvotes: 9

Views: 5974

Answers (2)

lrn
lrn

Reputation: 71828

It's not currently possible to override methods of enums.

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.

Upvotes: 15

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63769

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

Upvotes: 5

Related Questions