Dart Enums
Defining named constants and choices
š What are Enums?
Enums in Dart represent a fixed set of named constants. They're perfect for representing choices, states, or categories where you have a limited set of predefined values.
// Simple enum definition
enum Color {
red,
green,
blue,
yellow
}
// Using enum
Color favoriteColor = Color.blue;
print(favoriteColor); // Color.blue
Key Enum Concepts
Fixed Values
Predefined set of named constants
enum Status { pending, approved, rejected }
Index Property
Each enum value has an index
Status.pending.index // 0
Name Property
Get the string name of enum value
Status.approved.name // 'approved'
Switch Statements
Perfect for switch-case logic
switch (status) {
case Status.pending: break;
}
š¹ Basic Enum Usage
Here's how to create and use simple enums:
// Define an enum for days of the week
enum Day {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
}
void main() {
// Using enum values
Day today = Day.friday;
Day weekend = Day.saturday;
print('Today is: ${today.name}'); // Today is: friday
print('Index of today: ${today.index}'); // Index of today: 4
// Get all enum values
print('All days: ${Day.values}');
// Check enum equality
if (today == Day.friday) {
print('TGIF! It\'s Friday!');
}
// Using in switch statement
switch (today) {
case Day.monday:
print('Start of work week');
break;
case Day.friday:
print('End of work week');
break;
case Day.saturday:
case Day.sunday:
print('Weekend!');
break;
default:
print('Midweek day');
}
}
Output:
Today is: friday
Index of today: 4
All days: [Day.monday, Day.tuesday, Day.wednesday, Day.thursday, Day.friday, Day.saturday, Day.sunday]
TGIF! It's Friday!
End of work week
š¹ Enhanced Enums with Methods
Dart allows enums to have methods, properties, and constructors:
enum Planet {
mercury(3.303e+23, 2.4397e6),
venus(4.869e+24, 6.0518e6),
earth(5.976e+24, 6.37814e6),
mars(6.421e+23, 3.3972e6);
// Constructor
const Planet(this.mass, this.radius);
// Properties
final double mass; // in kilograms
final double radius; // in meters
// Method to calculate surface gravity
double get surfaceGravity => 6.67300E-11 * mass / (radius * radius);
// Method to calculate weight on this planet
double calculateWeight(double earthWeight) {
return earthWeight * surfaceGravity / Planet.earth.surfaceGravity;
}
// Override toString for better display
@override
String toString() => 'Planet: ${name.toUpperCase()}';
}
void main() {
double earthWeight = 70.0; // kg
print('Weight on different planets:');
for (Planet planet in Planet.values) {
double weight = planet.calculateWeight(earthWeight);
print('${planet}: ${weight.toStringAsFixed(2)} kg');
}
// Access specific planet properties
Planet earth = Planet.earth;
print('\nEarth details:');
print('Mass: ${earth.mass} kg');
print('Radius: ${earth.radius} m');
print('Surface Gravity: ${earth.surfaceGravity.toStringAsFixed(2)} m/s²');
}
Output:
Weight on different planets:
Planet: MERCURY: 26.36 kg
Planet: VENUS: 63.31 kg
Planet: EARTH: 70.00 kg
Planet: MARS: 26.53 kg
Earth details:
Mass: 5.976e+24 kg
Radius: 6378140.0 m
Surface Gravity: 9.80 m/s²
š¹ Enum with String Values
Create enums that work with specific string values:
enum HttpStatus {
ok(200, 'OK'),
notFound(404, 'Not Found'),
internalServerError(500, 'Internal Server Error'),
badRequest(400, 'Bad Request');
const HttpStatus(this.code, this.message);
final int code;
final String message;
// Static method to find status by code
static HttpStatus? fromCode(int code) {
for (HttpStatus status in HttpStatus.values) {
if (status.code == code) {
return status;
}
}
return null;
}
// Check if status indicates success
bool get isSuccess => code >= 200 && code < 300;
// Check if status indicates error
bool get isError => code >= 400;
@override
String toString() => '$code: $message';
}
void main() {
// Using enum with custom values
HttpStatus response = HttpStatus.ok;
print('Response: $response'); // Response: 200: OK
print('Is success: ${response.isSuccess}'); // Is success: true
print('Is error: ${response.isError}'); // Is error: false
// Find status by code
HttpStatus? status = HttpStatus.fromCode(404);
if (status != null) {
print('Found status: $status'); // Found status: 404: Not Found
}
// Handle different status codes
void handleResponse(HttpStatus status) {
switch (status) {
case HttpStatus.ok:
print('ā
Request successful');
break;
case HttpStatus.notFound:
print('ā Resource not found');
break;
case HttpStatus.internalServerError:
print('š„ Server error occurred');
break;
default:
print('ā ļø Other status: $status');
}
}
handleResponse(HttpStatus.notFound); // ā Resource not found
handleResponse(HttpStatus.ok); // ā
Request successful
}
Output:
Response: 200: OK
Is success: true
Is error: false
Found status: 404: Not Found
ā Resource not found
ā Request successful