Enum
The Power of Enums in Simplifying Code
Last updated
The Power of Enums in Simplifying Code
Last updated
This is a basic enum that everyone knows. But what if your enum could:
Define itself in JSON when received from a server
Automatically translate into different languages
List all its values dynamically
Search for values within its own methods
Shorten conditional statements significantly
In this article, I’ll show you a different way to use enums, turning a simple definition into a powerful and efficient coding tool.
Flutter is an object-oriented framework, and encapsulation is a key principle in OOP. Encapsulation hides the implementation details of an object and only allows interaction through public methods. This helps protect internal data, reduce errors, and improve maintainability.
Therefore, we can incorporate all these useful functionalities into a single enum, making it easier to use without worrying about its internal logic.
Defining a custom field in JSON is introduced in the official documentation of json_serializable: 🔗
Below is an example of how to set up an enum for json_serializable
. The enum retrieves data from JSON based on the 'code'
field and converts it into an enum value.
For example, with the following JSON:
The corresponding enum value will be:
We can replace 'code'
with any other field, such as 'title'
, depending on the requirements.
Example Code:
The second benefit that enums provide is reducing conditional code, making it easier to understand. Let's take a look at the following example:
Writing concise conditions makes the code more readable and easier to understand, as shown below:
New approach:
Old approach:
I will write a separate article on. multi-language translation. You can check it out here
Suppose I have the code
field value and I want to find out which enum it corresponds to. I can create a function like this:
With all the benefits listed above, using full-featured enums helps us write cleaner and faster code.
To generate a predefined template for your enums, consider using Mason. (If you're unfamiliar with Mason, check out this guide: )
You can also check out my enum template and create a custom one for yourself and your colleagues:
|