关于插件参数传递
按照以前的习惯,dart 端传递 map 参数,原生端根据 map 解析参数。
但由于 ts 支持将字符串直接转换成对应的 interface ,那么我们可以将 dart 的端的参数。
参数定义
比如 geolocator_ohos 中的 CurrentLocationSettingsOhos 在 dart 端的实现为如下:
Map<String, dynamic> toMap() {
return {
if (priority != null) 'priority': priority?.toInt(),
if (scenario != null) 'scenario': scenario?.toInt(),
if (maxAccuracy != null) 'maxAccuracy': maxAccuracy,
if (timeoutMs != null) 'timeoutMs': timeoutMs,
};
}
@override
String toString() {
return jsonEncode(toMap());
}
而在鸿蒙原生端,对于的 interface 是 CurrentLocationRequest
export interface CurrentLocationRequest {
priority?: LocationRequestPriority;
scenario?: LocationRequestScenario;
maxAccuracy?: number;
timeoutMs?: number;
}
值得注意的是,如果参数为 null,不要传递过去,比如 'priority': null , 如果传递过去,鸿蒙原生端会解析错误。不传递过去的话,会解析为 undefined,这也对应了 priority?: LocationRequestPriority 可选的意思。
可以使用
chatgpt直接将鸿蒙的interface转换成dart的类,并且增加toMap,fromMap,和注释。
插件传递
dart 端,将参数类以字符串的方式传递过去,并且用字符串的方式接受返回值。
@override
Future<Position> getCurrentPosition({
LocationSettings? locationSettings,
String? requestId,
}) async {
assert(
locationSettings == null ||
locationSettings is CurrentLocationSettingsOhos,
'locationSettings should be CurrentLocationSettingsOhos',
);
try {
final Duration? timeLimit = locationSettings?.timeLimit;
Future<dynamic> positionFuture =
GeolocatorOhos._methodChannel.invokeMethod(
'getCurrentPosition',
locationSettings?.toString(),
);
if (timeLimit != null) {
positionFuture = positionFuture.timeout(timeLimit);
}
return PositionOhos.fromString(await positionFuture);
}
}
在鸿蒙端, 将字符串直接转换成鸿蒙对应的 interface 。
let request: geoLocationManager.CurrentLocationRequest = JSON.parse(args);
并且将要返回的 interface 转换成字符串。
result.success(JSON.stringify(location));
当然了,这样有个问题,就是如果鸿蒙端修改了 interface 的属性名字,插件很难感知到(当然会报错)。