Welcome to this intricate examination of Enums in Flutter, an essential topic that often leaves developers scratching their heads. As Flutter developers, understanding Enums can significantly enhance our capability to write clean, efficient, and less-error-prone code.
This blog will break down the concepts of Enums and effectively elaborate on how to use them in Flutter. Buckle up as we embark on this journey to explore Enums in Flutter.
Enums, short for Enumerations, are a data type that includes a fixed number of constant values. They allow Flutter developers to assign predefined values to variables. The enumerated values that form an enumerated type must be different from each other. Each enumerated value defined in an Enum possesses an index value that represents its position in the Enum list, a zero-based position.
Enums' constrained functionality offers limited flexibility, which can be beneficial when creating variables that only accept a restricted set of values.
Enums are used ubiquitously in programming. In Flutter, Enums play a functional role in enhancing the readability and reliability of the code. Hence, understanding Enum in Flutter is imperative for writing clear and better-organized code.
1 enum Status { running, stopped, paused } 2 3 void main() { 4 print(Status.values); 5 } 6
As you can see in the Flutter example above, an enum declaration begins with the enum keyword followed by the enum name (Status, in this case). The enumeration list consists of named constant values (running, stopped, paused) defined within curly brackets.
The traditional way to access the enum's index value or connect a Flutter enum to a string is by using the index property or the toString() method, respectively. The index property returns the zero-based position of the enum value in the enumeration list, while the toString() method gives the enum's name as a String.
Flutter enum with values can utilize some built-in methods. One of them is values, which returns a list of all enum values in the order they were defined.
Let's move forward from the basics to the practical utilization. Learning through examples can help you to understand the concept with more clarity.
First, implement Enums in your Flutter code.
1 enum Color { red, green, blue } 2 3 void main() { 4 Color aColor = Color.blue; 5 6 switch (aColor) { 7 case Color.red: 8 print('Red as fire!'); 9 break; 10 11 case Color.green: 12 print('Green as grass!'); 13 break; 14 15 default: 16 print(aColor); 17 } 18 } 19
In this enum example, an Enum Color is declared with constant values red, green, and blue. Consequently, the Color.blue is assigned to a new variable aColor and a switch statement is written to handle each possible enum value.
Enums can be incorporated with a control flow statement – let's use a switch statement for demonstration.
1 enum OperatingSystem { ios, android, windows, linux } 2 3 void main() { 4 var currentOS = OperatingSystem.windows; 5 6 switch (currentOS) { 7 case OperatingSystem.ios: 8 print('iOS is up and running!'); 9 break; 10 11 case OperatingSystem.android: 12 print('Android is up and running!'); 13 break; 14 15 case OperatingSystem.windows: 16 print('Windows is up and running!'); 17 break; 18 19 case OperatingSystem.linux: 20 print('Linux is up and running!'); 21 break; 22 23 default: 24 print('Unknown OS'); 25 } 26 } 27
Here, we have an Enum OperatingSystem with four enumerated values. We then use a switch statement to handle each enum value in the currentOS variable.
In Flutter, Enums are not limited to just storing and manipulating simple enumerated values. They can also be utilized with collections like Lists, Sets, and Maps. That blend allows us to handle complex data structures more effectively.
Let's see a practical usage of enums with collections:
1 enum Inventory {apples, oranges, bananas} 2 3 void main() { 4 5 List<Inventory> fruitList = [Inventory.apples, Inventory.bananas]; 6 7 Set<Inventory> fruitSet = {Inventory.oranges, Inventory.bananas}; 8 9 Map<Inventory, int> fruitMap = { 10 Inventory.apples: 100, 11 Inventory.oranges: 80, 12 Inventory.bananas: 50 13 }; 14 15 print('Fruit list: $fruitList'); 16 print('Fruit set: $fruitSet'); 17 print('Fruit map: $fruitMap'); 18 } 19
In the above sample code, we have an Enum 'Inventory' with three enumerated values. We then use this Enum to create a List, a Set, and a Map.
This elucidates that Enums in Flutter offer flexibility to work with various kinds of data structures, providing us with opportunity to write more structured, organized, and less error-prone code. It's indeed yet another reason why understanding and practicing Enums is key to becoming a proficient Flutter developer.
As we go beyond the basic Enum properties and methods, we enter the realm of enhanced Enums, providing greater utility and efficiency.
Flutter (Dart) does not support adding methods or properties to an Enum. That's where the concept of "extension methods" comes into play, allowing developers to add new functionalities to existing Enums. This is also known as extending the Enum.
1 enum MyColor { Red, Green, Blue } 2 3 extension MyColorExtension on MyColor { 4 String get name { 5 switch (this) { 6 case MyColor.Red: 7 return 'Red'; 8 case MyColor.Green: 9 return 'Green'; 10 case MyColor.Blue: 11 return 'Blue'; 12 default: 13 return null; 14 } 15 } 16 } 17 18 void main() { 19 print(MyColor.Red.name); // prints out 'Red' 20 } 21
In the example above, we create a new method name in the MyColor Enum using an extension named MyColorExtension. The new name method now can be used with any Enum instances of MyColor.
Sometimes, we need to convert Flutter enum to string and fetch the Enum back from the string.
1 enum Fruit { Apple, Banana, Mango } 2 3 void main() { 4 // Enum to String 5 String fruit= Fruit.Apple.toString(); 6 7 // String to Enum 8 Fruit selectedFruit = Fruit.values.firstWhere((e) => e.toString() == fruit); 9 10 print(fruit); 11 print(selectedFruit); 12 } 13
In the sample code above, conversion from Enum to String is achieved by using the toString() method. On the contrary, to convert a string back to an Enum, we use firstWhere() to match the string with the Enums' values.
As we move deeper into Enums, it's important to point out some commonly made mistakes and the best ways to avoid them.
Enums can't have methods: Flutter doesn't allow Enums to contain methods. Developers often try to create a method inside an Enum and that leads to a compile-time error.
Enums can't be instantiated: A common mistake is trying to create an explicitly instantiated object of an Enum, which isn't possible because Enums don't have a public constructor.
Use Extensions for Enum methods: Since you can't add methods to an Enum, you can use an Extension as shown before in the Enhanced Enums section.
Always set expected values: When working with Enums, always make sure to have a value assigned for each enum status in your Flutter code to avoid null values.
Defining and using Enums in Flutter might be slightly intimidating at first glance. However, working with Flutter Enums becomes a much more manageable task once you delve deeper into their properties and methods through examples from the real world.
This blog post aims to help you decipher the role of Enums in Flutter and how to get the most out of them for a clean, efficient, and less error-prone code. To truly understand the power of these Enumerated types, you should continue experimenting and incorporating them into your Flutter projects.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.