Menu
Coddy logo textTech

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 icon

Challenge

Easy

Let'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 called TaskCategory that represents different types of tasks in a project. Each category should have:
    • A String label field for a human-readable name
    • An int priority field (1 being highest priority, 3 being lowest)
    • A const constructor that initializes both fields
    • Four enum values: bug (label: "Bug Fix", priority: 1), feature (label: "New Feature", priority: 2), documentation (label: "Documentation", priority: 3), and testing (label: "Testing", priority: 2)
    • A getter isUrgent that returns true if the priority is 1
    • A method describe() that returns a string in the format: [label] (Priority: [priority])
    Your enum should also implement Comparable<TaskCategory> so tasks can be sorted by priority (lower priority number = comes first).
  • 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 where isUrgent is true

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 Fix

Cheat 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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming