Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An enum property in Dart is a final instance variable declared within an enhanced enumeration, allowing constant data to be associated with each discrete enum value. Since Dart 2.17, enums function as specialized classes that can encapsulate state, require const constructors, and expose properties directly on their instances.

Syntax and Declaration

To define properties within an enum, you must declare the instance variables, provide a constant generative constructor, and invoke that constructor for each enum value.
enum HttpStatus {
  ok(200, 'OK'),
  badRequest(400, 'Bad Request'),
  internalServerError(500, 'Internal Server Error');

  // 1. Properties must be final
  final int code;
  final String message;

  // 2. Constructor must be const
  const HttpStatus(this.code, this.message);
}

Technical Constraints

When implementing enum properties, the Dart compiler enforces strict structural rules:
  1. Immutability: All instance variables declared in an enum must be final. Enums represent a fixed, constant set of values, and their internal state cannot mutate at runtime.
  2. Constant Constructors: Any generative constructor defined in the enum must be prefixed with the const keyword.
  3. Value Instantiation: The discrete enum values must be declared at the very beginning of the enum body. They act as static constant invocations of the enum’s constructor.
  4. Semicolon Termination: If the enum contains properties, constructors, or methods, the list of enum values must be explicitly terminated with a semicolon (;) rather than a comma.

Accessing Properties

Enum properties are accessed using standard dot notation on the enum instance, identical to accessing properties on a standard class object.
void evaluateStatus() {
  final status = HttpStatus.badRequest;
  
  // Accessing the final properties
  int statusCode = status.code;          // 400
  String statusMessage = status.message; // 'Bad Request'
}

Computed Properties (Getters)

In addition to stored final variables, enums can declare computed properties using getters. These do not require constructor initialization and can derive their values dynamically based on the current enum instance (this).
enum FilePermission {
  read(1),
  write(2),
  execute(4);

  final int bitmask;

  const FilePermission(this.bitmask);

  // Computed property
  bool get isExecutable => this == FilePermission.execute;
}
Master Dart with Deep Grasping Methodology!Learn More