Enums with Methods
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 88 of 110.
In Dart, enums aren't just simple lists of constants - they can have fields, constructors, and methods, making them powerful mini-classes. This is called enhanced enums, and it lets you attach behavior and data directly to each enum value.
enum Status {
pending('Waiting'),
approved('Accepted'),
rejected('Denied');
final String displayName;
const Status(this.displayName);
bool get isFinalized => this == approved || this == rejected;
}
void main() {
var status = Status.pending;
print(status.displayName); // Waiting
print(status.isFinalized); // false
print(Status.approved.isFinalized); // true
}Each enum value calls the constructor with its specific arguments. The constructor must be const, and all fields must be final. You can add getters and methods that work with the enum's data or compare against other values.
Enhanced enums can also implement interfaces, giving them even more flexibility:
enum Priority implements Comparable<Priority> {
low(1),
medium(2),
high(3);
final int level;
const Priority(this.level);
@override
int compareTo(Priority other) => level.compareTo(other.level);
}
void main() {
var tasks = [Priority.high, Priority.low, Priority.medium];
tasks.sort();
print(tasks); // [Priority.low, Priority.medium, Priority.high]
}Enhanced enums are ideal when you have a fixed set of values that each need associated data or behavior - like status codes with messages, priorities with levels, or directions with coordinates.
Challenge
EasyLet's build a task management system using enhanced enums! You'll create an enum that represents different task categories, each with its own properties and behaviors that help organize and prioritize work.
You'll organize your code into two files:
task_category.dart: Create an enhanced enum calledTaskCategorythat represents different types of tasks in a project. Each category should have:- A
String labelfield for a human-readable name - An
int priorityfield (1 being highest priority, 3 being lowest) - A
constconstructor that initializes both fields - Four enum values:
bug(label: "Bug Fix", priority: 1),feature(label: "New Feature", priority: 2),documentation(label: "Documentation", priority: 3), andtesting(label: "Testing", priority: 2) - A getter
isUrgentthat returnstrueif the priority is 1 - A method
describe()that returns a string in the format:[label] (Priority: [priority])
Comparable<TaskCategory>so tasks can be sorted by priority (lower priority number = comes first).- A
main.dart: Import your task category enum and demonstrate its capabilities:- Create a list containing all four task categories in this order:
feature,bug,documentation,testing - Print each category's description using the
describe()method, one per line - Print an empty line
- Sort the list by priority and print
After sorting by priority: - Print each sorted category's label, one per line
- Print an empty line
- Print
Urgent tasks: - Loop through the original order (
feature,bug,documentation,testing) and print only the labels of categories whereisUrgentis true
- Create a list containing all four task categories in this order:
This challenge combines enhanced enum features: fields, constructors, getters, methods, and implementing interfaces - all working together to create a useful task categorization system!
Expected output:
New Feature (Priority: 2)
Bug Fix (Priority: 1)
Documentation (Priority: 3)
Testing (Priority: 2)
After sorting by priority:
Bug Fix
New Feature
Testing
Documentation
Urgent tasks:
Bug FixCheat sheet
Enhanced enums in Dart can have fields, constructors, and methods, making them powerful mini-classes that attach behavior and data to each enum value.
Basic enhanced enum with fields and constructor:
enum Status {
pending('Waiting'),
approved('Accepted'),
rejected('Denied');
final String displayName;
const Status(this.displayName);
}Key requirements:
- Constructor must be
const - All fields must be
final - Each enum value calls the constructor with specific arguments
Enhanced enums can include getters and methods:
enum Status {
pending('Waiting'),
approved('Accepted'),
rejected('Denied');
final String displayName;
const Status(this.displayName);
bool get isFinalized => this == approved || this == rejected;
}Enhanced enums can implement interfaces like Comparable:
enum Priority implements Comparable<Priority> {
low(1),
medium(2),
high(3);
final int level;
const Priority(this.level);
@override
int compareTo(Priority other) => level.compareTo(other.level);
}Use enhanced enums when you have a fixed set of values that each need associated data or behavior.
Try it yourself
import 'task_category.dart';
void main() {
// TODO: Create a list containing all four task categories in this order:
// feature, bug, documentation, testing
// TODO: Print each category's description using describe(), one per line
// TODO: Print an empty line
// TODO: Sort the list by priority
// TODO: Print "After sorting by priority:"
// TODO: Print each sorted category's label, one per line
// TODO: Print an empty line
// TODO: Print "Urgent tasks:"
// TODO: Loop through the original order (feature, bug, documentation, testing)
// and print only the labels of categories where isUrgent is true
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor