schultek/dart_mappable

"catchall" enum?

Closed this issue · 1 comments

Wondering if there is an easy way to implement an enum mapper that designates one value as a "catchall" rather than throwing an error if an enum is not within the known set.

For example if I am building a Flutter app and today the app and the server are both sync'ed, we have an enum like:

@MappableEnum()
enum PreferredContactMethod {
  PhoneCall, Email, SMS
}

and next month the developers implement WhatsApp and WeChat. People who have an updated app will be able to receive these enum values from the server, but older clients will throw an error when the server sends PreferredContactMethod.WhatsApp and that is not a known value. Getting your entire userbase to upgrade their app can take years.

Instead, what if we anticipated the issue and built the initial enum like:

@MappableEnum()
enum PreferredContactMethod {
 @MappableCatchall() Unknown, 
 PhoneCall, 
 Email, 
 SMS
}

and any value returned from the server that wasn't a known value would be routed to Unknown. This is preferred over throwing an error, the client can display a 'please update' message or default to a different choice or cleanly handle some other way.

Thank you.

EDIT: just found out this exists in json_mappable with the JsonKey.unknownEnumValue annotation

Use @MappableEnum(defaultValue: PreferredContactMethod.Unknown)