You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.7 KiB

import 'dart:convert';
import 'package:flutter/services.dart';
/// 代理服务事件类型
enum AmapServiceEventType {
/// 导航启动
starte,
///导航结束
stope,
update,
/// 错误
error,
/// 未知事件
unknown,
}
/// 代理服务事件数据
class AmapServiceEvent {
/// 事件类型
final AmapServiceEventType type;
/// 事件数据
final Map<String, dynamic> 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<AmapServiceEvent>? _eventStream;
// 内部构造函数
AmapService._internal() {
_eventChannel = const EventChannel(
'com.yunqiinnovation.amap_service/events',
);
}
/// 获取事件流
Stream<AmapServiceEvent> get events {
_eventStream ??= _eventChannel.receiveBroadcastStream().map((event) {
try {
final Map<String, dynamic> eventMap = jsonDecode(event);
final String eventName = eventMap['event'];
final Map<String, dynamic> 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<void> start() async {
await _methodChannel.invokeMethod('start');
}
Future<void> open(String start, String end, String ntype) async {
await _methodChannel.invokeMethod('open', {
'startpos': start,
"endpos": end,
"ntype": ntype,
});
}
Future<void> stop() async {
await _methodChannel.invokeMethod('stop');
}
// 销毁
Future<void> dispose() async {}
}