My app is connected to a custom made peripheral and draws some values from it as ints which I want to convert to enums to streamline the app code.
As the hardware evolves overtime, it is of known fact that new values will come.
In my Flutter app, I handle known values (by the time of app writing) through enum extensions, providing an 'unknown' value as follows:
// Battery live data originator protocol
enum BatteryLiveDataProtocol {
unknown, // 0
rs485, // 1
ttl, // 2
canbus, // 3
uart, //4
;
}
extension BatteryLiveDataProtocolExtension on BatteryLiveDataProtocol {
/// Build the enum out of the int number
static BatteryLiveDataProtocol fromNumber(int number) {
switch (number) {
case 1:
return ttl;
case 2:
return rs485;
case 3:
return canbus;
case 0:
default:
return unknown;
}
}
/// Returns the number correpsonding to the enum
int get number {
switch (this) {
case rs485:
return 1;
case ttl:
return 2;
case canbus:
return 3;
case unknown:
default:
return 0;
}
}
As you can see, this code support future version in a quite handily:
const futureValue = 13;
final p = BatteryLiveDataProtocol.fromNumber(futureValue);
Since the introduction of Dart 2.17 (& Flutter 3) I'd like to take advantage of the enhanced enums as follows:
// Battery live data originato protocol
enum BatteryLiveDataProtocol {
unknown(),
rs485(1),
ttl(2),
canbus(3),
uart(4),
;
const BatteryLiveDataProtocol(this.value);
final num value;
}
But then how can I handle future enum values?
I could do that, everywhere I want to convert the int to the enum:
BatteryLiveDataProtocol p;
try {
const futureValue = 13;
p = BatteryLiveDataProtocol(futureValue);
} catch(e) {
p = BatteryLiveDataProtocol.unknown;
}
But this is cumbersome, isn't it? It'll be cool to have the possibility to provide the body of const BatteryLiveDataProtocol(this.value); ourselves.
[UPDATE] Btw, not sure it was clear enough, but it is still possible to create a static function within the enhanced enum as follows:
static BatteryLiveDataProtocol fromValue(int v) {
BatteryLiveDataProtocol p;
try {
p = BatteryLiveDataProtocol[v];
} catch (e) {
p = unknown;
}
return p;
}
And use it as follows:
const futureValue = 13;
final p = BatteryLiveDataProtocol.fromValue(futureValue);
// Makes p being set to "unknown".
So my question #1: is there a better/clever (aka handy) way to handle future values?
Question #2: Others language handle future enum (in Swift for example): is there a way to generate unknown(actualValue) as a dynamic enum value?