import 'dart:convert'; import 'package:flutter/services.dart'; /// 代理服务事件类型 enum AmapServiceEventType { /// 导航启动 starte, ///导航结束 stope, update, /// 错误 error, /// 未知事件 unknown, } /// 代理服务事件数据 class AmapServiceEvent { /// 事件类型 final AmapServiceEventType type; /// 事件数据 final Map data; AmapServiceEvent({required this.type, required this.data}); @override String toString() => 'AmapServiceEvent(type: $type, data: $data)'; } class AmapService { static final AmapService _instance = AmapService._internal(); /// 获取单例 factory AmapService() => _instance; // 方法通道 final MethodChannel _methodChannel = const MethodChannel( 'com.yunqiinnovation.amap_service', ); // 事件通道 - 简化为只使用数据和状态通道 late final EventChannel _eventChannel; static Stream? _eventStream; // 内部构造函数 AmapService._internal() { _eventChannel = const EventChannel( 'com.yunqiinnovation.amap_service/events', ); } /// 获取事件流 Stream get events { _eventStream ??= _eventChannel.receiveBroadcastStream().map((event) { try { final Map eventMap = jsonDecode(event); final String eventName = eventMap['event']; final Map eventData = eventMap['data']; // 将事件名称转换为枚举 final AmapServiceEventType type = _stringToEventType(eventName); return AmapServiceEvent(type: type, data: eventData); } catch (e) { return AmapServiceEvent( type: AmapServiceEventType.unknown, data: {'error': e.toString(), 'rawEvent': event}, ); } }); return _eventStream!; } /// 将字符串事件名转换为枚举类型 static AmapServiceEventType _stringToEventType(String eventName) { switch (eventName) { case 'amap_starte': return AmapServiceEventType.starte; case 'amap_stope': return AmapServiceEventType.stope; case 'amap_update': return AmapServiceEventType.update; case 'amap_error': return AmapServiceEventType.error; default: return AmapServiceEventType.unknown; } } Future start() async { await _methodChannel.invokeMethod('start'); } Future open(String start, String end, String ntype) async { await _methodChannel.invokeMethod('open', { 'startpos': start, "endpos": end, "ntype": ntype, }); } Future stop() async { await _methodChannel.invokeMethod('stop'); } // 销毁 Future dispose() async {} }