Last active
September 7, 2020 22:30
-
-
Save boukeversteegh/f67e58f500f3c0c7126640bb43e11197 to your computer and use it in GitHub Desktop.
Dart class as enum template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
print(Number.one); | |
print(Number.two); | |
print(Number.three); | |
print(Number.fromInt(1)); | |
print(Number.fromInt(2)); | |
print(Number.fromInt(3)); | |
print(Number.fromString('1')); | |
print(Number.fromString('2')); | |
print(Number.fromString('3')); | |
print(Number.fromString('4')); // Uncaught Error: Invalid argument(s): Invalid Number: 4 | |
} | |
class Number { | |
// possible enum values | |
static const one = Number._('one', 1); | |
static const two = Number._('two', 2); | |
static const three = Number._('three', 3); | |
// public enum fields | |
final int value; | |
// string representation of enum value | |
final String _string; | |
// private const constructor | |
const Number._(this._string, this.value); | |
// mappable values | |
static const _values = {1: one, 2: two, 3: three}; | |
// factories | |
factory Number.fromInt(int value) => _values[value] ?? (throw ArgumentError('Invalid Number: $value')); | |
factory Number.fromString(String value) => Number.fromInt(int.parse(value)); | |
@override | |
String toString() => '$runtimeType.$_string'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment