Flutter/Dart Enums & Extension

Shorol
Nov 22, 2022

How Enums and Extension work in every framework to maintain and write easy code.

Understating Enums:

enum DeviceName{ Apple, Nokia }

print(DeviceName.Apple.toString()) -> DeviceName.Apple : That's mean your full enum class
values will be printed as string.

print(DeviceName.Apple.name) -> Apple : It will only print your name enum value as string. //Best practice

So before comparing, assigning keep in mind what the actual value your are using.


Or you can use extension

##Declare Enums
enum UserType{ bot, doctor, patient }


##String to Enum

extension UserType on String {
Topic get topic {
switch (this) {
case 'bot':
return UserType.bot;
case 'doctor':
return UserType.doctor;
case 'patient':
return UserType.patient;
}
}
}


## Enum to string
extension UserTypeExtension on UserType {
String get string {
switch (this) {
case UserType.bot:
return 'bot';
case UserType.doctor:
return 'doctor';
case UserType.patient:
return 'patient';
}
}
}

--

--

Shorol
0 Followers

Software Engineer, Tech Enthusiast, Build for impact. A dreamer