Enums are a good way to represent a determined set of values, which I use often. They're good when used in code, or when matching some values returned from your backend APIs with the client code for example.
But moving on the UI, you cannot present them as-is to the end user, they must be converted into something more readable.
In dart, you can use Enum.values, which returns a list of all the Keys registered. You can also define Maps, having an Enum used as key, and any object as value.
This is exactly how this code works. It was more an excercise for checking my dev skills to be honest, I started to use Dart less than 3 weeks ago, so please forgive any error (suggestions are welcome!) (:)
The example shows how to map a String, or a Color, but you're free to create your own, it's just a matter of writing some lines of code.
- Create the new class, and define which object will be mapped, now it's a int:
abstract class EnumIntegerMapper<Enum> extends EnumObjectMapper<Enum, int> {
- (optional) If you need to, update the validation condition:
@override
bool invalidCondition(int value) => super.invalidCondition(value) || value < 0;
Note: You're not obliged to call the super method, in this case we are mapping an integer, which cannot be null (super.invalidCondition is a null check), so it would be better to do something like that:
@override
bool invalidCondition(int value) => value < 0 || value > 10;
The type of value
will be equal to the mapped value's type, remember to update your function in case of overriding!
- (optional) Update the error message, for validation failures:
@override
String validationError(Enum key, int value) => 'Number for key: $key is out of range ($value)!';
- Create another class, to define which Enum will be mapped to values:
class MyEnumToIntegerMapper extends EnumIntegerMapper<MyEnum, int> {
You are ready to use the new helpers. As you can imagine, two methods are available. I'm using the classes defined in the other files here:
String orderStatus = OrderStatusLabelMapper().getValue(OrderStatus.INITIALIZED);
// orderStatus = 'Initialized';
OrderStatus inverseValue = OrderStatusLabelMapper().getKey(orderStatus);
// inverseValue = OrderStatus.INITIALIZED;
Eventually, the code can be made even more generic, in order to accept any kind of object, not only an Enum as input. But let's stop here for the moment.
I hope that this code may have helped you, probably it can be improved, but also adapted for other usages. I think that it's a good starting point to understand how inheritance works.
Maybe with a mixin, more functionalities can be added, for example another validation rule, or a pre-processing function to transform the input values before they're mapped (grouping?). It's up to your fantasy! ;)
.. Dart is a nice language!
Happy coding! ;)