Mastering enum in Flutter – Clean, Scalable & Pro-Level Usage
Teqani Blogs
Writer at Teqani
When I started writing Flutter apps, I used enums like most people do — as constants. But over the years, I realized enums are more than just fancy lists. Used right, they clean your code, power your UI logic, and scale with your app. This article dives deep into leveraging enums effectively to enhance your Flutter development.
1. Easy Serialization for APIs & Storage
Need to save enum values to local storage or send them over the network? No need for manual mapping or extra helper methods — Dart’s enums have a built-in .name property that makes this ridiculously simple. And with .values.byName(), parsing them back is just as clean.
enum Status { pending, approved, rejected }
// To JSON or SharedPreferences
final String saved = Status.approved.name; // "approved"
// From JSON or storage
final Status parsed = Status.values.byName(saved); // Status.approved
2. Apply Enum-Based Builders
Instead of cluttering your UI with switch or if-else blocks, let enums build their own widgets using extensions. This pattern allows your enum to decide what widget to render, making your widget tree cleaner and easier to maintain.
enum LoaderType { shimmer,custom, circular }
extension LoaderX on LoaderType {
Widget build() => switch (this) {
LoaderType.shimmer => ShimmerLoader(),
LoaderType.custom => CustomLoader(),
LoaderType.circular => CircularProgressIndicator(),
};
}
3. Enum as a UI Builder Class
Instead of cluttering your UI code with switch statements, you can turn enums into self-contained widget factories by giving them fields, constructors, and builder methods. This makes your UI components scalable, testable, and super clean.
enum ButtonType {
primary(icon: Icons.check, color: Colors.blue),
danger(icon: Icons.warning, color: Colors.red);
final IconData icon;
final Color color;
const ButtonType({required this.icon, required this.color});
Widget build(String label, VoidCallback onPressed) {
return ElevatedButton.icon(
onPressed: onPressed,
icon: Icon(icon),
label: Text(label),
style: ElevatedButton.styleFrom(backgroundColor: color),
);
}
}
Usage:
ButtonType.danger.build("Delete", () => print("Deleted"));
Enums aren’t just constants — they can be a powerful tool that make your code cleaner, smarter, and easier to scale. Leverage these enum hacks to write more efficient Flutter code.
All blogs are certified by our company and reviewed by our specialists
Issue Number: #b1f5369b-c3bb-4f7f-b591-7398a97a2931