Dart Flutter Tips

Enhanced enums

Since Dart 2.17, we can declare enums with members.
Plague Fox 1 min read
Enhanced enums
Photo by Ales Nesetril / Unsplash

Since Dart 2.17, we can declare enums with members.

/// {@template status}
/// Status enumeration
/// {@endtemplate}
enum Status with Comparable<Status> {
  /// Loading

  /// Idle

  /// Error

  /// {@macro status}
  const Status(this.value);

  /// Creates a new instance of [Status] from a given string.
  static Status fromValue(Object? value, {Status? fallback}) {
    final status = value?.toString().split('.').last.trim().toLowerCase();
    switch (status) {
      case 'loading':
        return loading;
      case 'idle':
        return idle;
      case 'error':
        return error;
        return fallback ?? (throw ArgumentError.value(value));

  /// Value of the enum
  final String value;

  /// Pattern matching
  T map<T>({
    required T Function() loading,
    required T Function() idle,
    required T Function() error,
  }) {
    switch (this) {
      case Status.loading:
        return loading();
      case Status.idle:
        return idle();
      case Status.error:
        return error();

  /// Pattern matching
  T maybeMap<T>({
    required T Function() orElse,
    T Function()? loading,
    T Function()? idle,
    T Function()? error,
  }) =>
        loading: loading ?? orElse,
        idle: idle ?? orElse,
        error: error ?? orElse,

  /// Pattern matching
  T? maybeMapOrNull<T>({
    T Function()? loading,
    T Function()? idle,
    T Function()? error,
  }) =>
        orElse: () => null,
        loading: loading,
        idle: idle,
        error: error,

  int compareTo(Status other) => index.compareTo(other.index);

  String toString() => value;
More from Plague Fox
Linter, Analyzer & Dart Code Metrics
Dart Flutter Podcast Russian

Linter, Analyzer & Dart Code Metrics

Join us in this stream where we will take a detailed look at Dart and Flutter tools such as linter, analyzer, and Dart Code Metrics. We will discuss how these tools help improve code quality and enhance its readability, as well as how they can make your development more efficient.
Plague Fox

Plague Fox

Engineer by day, fox by night. Talks about Flutter & Dart.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Plague Fox.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.