Sitemap
Press enter or click to view image in full size
Photo by Luca Upper on Unsplash

FLUTTER MASTERCLASS

Using Enums like a Pro in Flutter

--

Whoever started using Dart after developing for example in Kotlin, was disappointed with all the limitations that it imposed. One of them was enum class. Having enumerated values alone was fine, but something more? You had to use extensions, right? Sometimes a few of them.

Let’s remind ourselves how such code could’ve looked like. Below is the set of activities. At some point we want to assign a number to each activity and a string value. Maybe our backend returns a number, but we of course don’t want to manipulate with magic numbers in our beautiful app code. Instead, we decide to use enums.

enum ActivityType {
running,
climbing,
hiking,
cycling,
ski
}

extension ActivityTypeNumber on ActivityType {
int get number {
switch (this) {
case ActivityType.running:
return 1;
case ActivityType.climbing:
return 2;
case ActivityType.hiking:
return 5;
case ActivityType.cycling:
return 7;
case ActivityType.ski:
return 10;
}
}
}
extension ActivityTypeValue on ActivityType {
String get value {
switch (this) {
case ActivityType.running:
return 'Running';
case ActivityType.climbing:
return 'Climbing';
case ActivityType.hiking:
return 'Hiking';
case…

--

--

No responses yet