Created
June 8, 2022 18:17
-
-
Save repentsinner/8868f39cd815af9e60989040dc41db89 to your computer and use it in GitHub Desktop.
Dart enhanced enum parser
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
import 'dart:convert'; | |
enum ApiParam { | |
foo('FOO_KEY'), | |
bar('BAR_INFO'), | |
baz('BAZ_THING'), | |
; | |
final String param; | |
const ApiParam(this.param); | |
@override | |
String toString() => param; | |
static ApiParam parse(String s) => | |
ApiParam.values.firstWhere(((e) => e.toString() == s)); | |
} | |
void main() { | |
// send a typesafe message off to an external service with funky keys | |
print(jsonEncode({ApiParam.foo.toString():'yep'})); | |
double? bar; | |
// receive a stringly typed message | |
var d = jsonDecode('{"id":"BAR_INFO", "value":21.1}'); | |
ApiParam p = ApiParam.parse(d['id'] as String); | |
switch (p) { | |
case ApiParam.foo: | |
case ApiParam.bar: | |
bar = d['value']; | |
break; | |
case ApiParam.baz: | |
} | |
print(bar ?? ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment