vnote_device_plugin_method_channel.dart 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:flutter/foundation.dart';
  4. import 'package:flutter/services.dart';
  5. import 'event_entrepot.dart';
  6. import 'vnote_device_plugin_platform_interface.dart';
  7. /// An implementation of [VnoteDevicePluginPlatform] that uses method channels.
  8. class MethodChannelVnoteDevicePlugin extends VnoteDevicePluginPlatform {
  9. /// The method channel used to interact with the native platform.
  10. @visibleForTesting
  11. final methodChannel = const MethodChannel('vnote_device_plugin');
  12. final eventChannel = const EventChannel("vnote_device_plugin_event");
  13. StreamSubscription<dynamic>? _eventChannelSubcription;
  14. @override
  15. Future<String?> getPlatformVersion() async {
  16. final version =
  17. await methodChannel.invokeMethod<String>('getPlatformVersion');
  18. return version;
  19. }
  20. @override
  21. Future<void> callAction(String action, Map<String, dynamic> data) async {
  22. data["ACTION"] = action;
  23. await methodChannel.invokeMethod(
  24. "callAction",
  25. {
  26. "request": jsonEncode(data),
  27. },
  28. );
  29. }
  30. @override
  31. Future<void> init() async {
  32. _eventChannelSubcription ??=
  33. eventChannel.receiveBroadcastStream().listen(_onEventReceived);
  34. return methodChannel.invokeMethod("init");
  35. }
  36. void _onEventReceived(dynamic event) {
  37. final String jsonText = event;
  38. final jsonMap = jsonDecode(jsonText);
  39. EventEntrepot.instance.receiveEvent(jsonMap);
  40. }
  41. }