Search code examples
dartenums

Apply same extension for multiple enums in dart


Is there a possibility to apply the same dart extension to multiple enums? Here is my enum and extension.

enum Currency {
  EUR, INR, USD, CNY, JPY, GBP
}

extension ParseToString on Currency {
  String toShortString() {
    return this.toString().split('.').last;
  }
}

Is it possible to make it like

enum InvoiceStatus {
  DRAFT, SENT, PAID, PARTIALLY_PAID
}

extension ParseToString on Currency, InvoiceStatus {
  String toShortString() {
    return this.toString().split('.').last;
  }
}

Solution

  • While there isn't a way to add an extension to multiple enums, since dart 2.14 all enums extends a common interface: Enum. That allows you to add an extensions to all enums:

    extension on Enum {
      String toShortString() {
        return this.toString().split('.').last;
      }
    }
    

    after so you can use .toShortString() to any enum object.