Skip to content

Instantly share code, notes, and snippets.

@mt40
Created September 17, 2019 04:02
Show Gist options
  • Save mt40/11bb499e1f6621276227bd7e49b72fd3 to your computer and use it in GitHub Desktop.
Save mt40/11bb499e1f6621276227bd7e49b72fd3 to your computer and use it in GitHub Desktop.
Dart Static Enum Pattern
/// As of Dart 2.5, `enum` can still only support very simple use case.
/// To have a "rich enum" with custom value type and methods, we need
/// to use static class member. This is an example implementation.
void main() {
final s1 = 'done', s2 = 'waiting';
final done = Enum.parse(Status.values, s1);
final waiting = Enum.parse(Status.values, s2);
print(done);
print(waiting);
print(done.isGood);
}
abstract class Enum<A> {
final A _value;
A get value => _value;
Enum(this._value);
@override
String toString() => _value.toString();
/// Returns an instance of enum `B` by taking the first
/// value equals to `a` from the given choices.
static B parse<A, B extends Enum<A>>(List<B> choices, A a) {
return choices.firstWhere((c) => c.toString() == a);
}
}
class Status extends Enum<String> {
static final done = Status('done');
static final waiting = Status('waiting');
static final values = [done, waiting];
Status(String s) : super(s);
// Sample method
bool get isGood => this == done;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment