Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR DART

enum flutter 3

/// Adding members
/// With enhanced enums, you can add any member to your enum as long as the constructor is const.

/// This also means that you can add getters or methods to existing enums, for example:

enum Cake {
  cherry,
  apple,
  strawberry;

  String get description => '$name cake';
}
/// Generics
/// Enhanced enum classes also enable you to use generics for you enums. If you combine this with members, you can do the following:

enum Bar<T extends Object> {
  number<int>(42),
  name<String>('creativecreatorormaybenot'),
  baz(true); // Note that type inference also works.

  const Bar(this.value);
  final T value;
}
/// Mixins and interfaces
/// In addition to declaring members, you can also mixin mixins and implement interfaces with enhanced enums and override any missing implementations.

mixin Foo {
  int get n;
}

abstract class Bar {
  void printNumber();
}

enum Baz with Foo implements Bar {
  one(1),
  two(2);
  
  const Baz(this.n);

  @override
  final int n;

  @override
  void printNumber() => print(n);
}
/// Multiple arguments
/// Finally note that even if I did not make use of it in any of the examples above, it is possible to have an arbitrary number of arguments (and an initializer list):

enum Foo {
  bar(42, description: 'The answer to life, the universe, and everything.'),
  baz(0, enabled: false, description: 'noop');

  const Foo(
    int number, {
    this.enabled = true,
    required this.description,
  }) : n = number;
  final int n;
  final bool enabled;
  final String description;
}
 
PREVIOUS NEXT
Tagged: #enum #flutter
ADD COMMENT
Topic
Name
2+3 =