Created
July 14, 2020 14:03
-
-
Save minikin/091dc8c6b4753779f5dd066ba6a90e0a to your computer and use it in GitHub Desktop.
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'; | |
void main() { | |
final event = EposEvent(EposEventType.connect, {'key': 'value'}); | |
final jsonObject = event.toJson(); | |
print(event); | |
print(jsonObject); | |
} | |
class EposEvent { | |
final EposEventType type; | |
final Map<String, Object> data; | |
const EposEvent(this.type, this.data); | |
Map<String, Object> toJson() { | |
return { | |
'type': type.keyFromEventTypeMap, | |
'data': data, | |
}; | |
} | |
@override | |
String toString() => jsonEncode(toJson()); | |
static EposEvent fromJson(Map<String, Object> json) { | |
return EposEvent( | |
eventTypesMap[json['type']], | |
json['data'], | |
); | |
} | |
} | |
final Map<String, EposEventType> eventTypesMap = { | |
'DISCOVERY': EposEventType.discovery, | |
'CONNECT': EposEventType.connect, | |
'DISCONNECT': EposEventType.disconnect, | |
'RECONNECTING': EposEventType.reconnecting, | |
'RECONNECT': EposEventType.reconnect, | |
'SCAN': EposEventType.scan | |
}; | |
enum EposEventType { | |
discovery, | |
connect, | |
disconnect, | |
reconnecting, | |
reconnect, | |
scan | |
} | |
extension EposEventTypeExtension on EposEventType { | |
String get keyFromEventTypeMap { | |
return eventTypesMap.keys.firstWhere((k) => eventTypesMap[k] == this); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://dartpad.dev/091dc8c6b4753779f5dd066ba6a90e0a