I have a class & enum that looks like this
enum UnitsOfMeasurement {
meters,
feet,
inches,
centimeters,
millimeters,
}
class MyMaterial {
final double height;
final UnitsOfMeasurement unitOfMeasurement;
MyMaterial({required this.height, required this.unitOfMeasurement});
}
The user can change the unit of measurment and then when I display the height I have utility functions to parse from and to each unit of measurment (from meters to inches, from inches to feet, etc..).
I would like to see if it’s possible to include this logic into the enum, or if there is some other better method than having multiple utility functions to handle this logic.
2
Answers
Add a customized getter method inside the class
now call the
convertedHeight
like this:Edit (cred to Randal):
Used as:
Or in terms of the
MyMaterial
class:Original answer:
You don’t need multiple utility functions. One mapping/factor table and one method/function is enough. Place the method and table at a point of your liking.
There are a few way to do this. I don’t think using enhanced enums is the cleanest approach. I think the cleanest approach is a translation/mapping/factor table and a simple method in the
MyMaterial
class. This is shown last of the examples.Enhanced enum way:
Extension method on enum way:
Simple method on MyMaterial:
You could obviously use the enhanced enum method, or the extension method inside the
MyMaterial
class method if you don’t like to have the conversion logic stored in theMyMaterial
class. Then you would just do this in theMyMaterial
method:Mapping/Factor logic:
All options use a factor mapping that looks like this. Not completed though, that is for the OP to add 🙂 :
Used like this:
DartPad with all the code:
https://dartpad.dev/?id=2f750de1fbc1da5b39555248e24c6c04