概念:
Flutter 会将资料通过 engine 层传送到 native 层,native 处理完了之後会有一个结果返回,即callback,也就是BinaryMessenger
的send
函式返回结果是一个 Future 型别的原因
反过来,改为 native 向 flutter 传送讯息,flutter 返回结果,那麽返回的这部分就对应着接收讯息资料的实现,处理结果通过 callback 回拨给 native
Flutter 传送讯息流程:
传送过程从 send 开始,返回值是 Future,在 _sendPlatformMessage
中使用 Completer
将 Future 转成了回拨函式:
Future<ByteData?> _sendPlatformMessage(String channel, ByteData? message) {
final Completer<ByteData?> completer = Completer<ByteData?>();
// ui.PlatformDispatcher.instance is accessed directly instead of using
// ServicesBinding.instance.platformDispatcher because this method might be
// invoked before any binding is initialized. This issue was reported in
// #27541. It is not ideal to statically access
// ui.PlatformDispatcher.instance because the PlatformDispatcher may be
// dependency injected elsewhere with a different instance. However, static
// access at this location seems to be the least bad option.
ui.PlatformDispatcher.instance.sendPlatformMessage(channel, message, (ByteData? reply) {
try {
completer.complete(reply);
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'services library',
context: ErrorDescription('during a platform message response callback'),
));
}
});
return completer.future;
}
透过呼叫 ui.PlatformDispatcher.instance.sendPlatformMessage
准备传送讯息至 engine 层,再由engine 层与native 层进行讯息的处理,在Native 端,以android 为例,android 中也有一个类似於defaultBinaryMessenger
的物件platformMessageHandler
,handleMessageFromDart
方法接收Flutter 传来的讯息,并在其中从messageHandlers
中取出对应 channel 的 handler(通过 setMessageHandler 设定),呼叫其 onMessage
方法进行处理,replyId 也就是之前Flutter 在sendPlatformMessage
生成的 responseId,它被封装成了 Reply,处理完讯息之後呼叫 Reply 的 reply 方法,将结果回传给 flutter 的 _sendPlatformMessage
函式,并用Completer
进行回拨,完成传送
Flutter 接收讯息流程:
基本上就是传送流程的反过来,当然细节上会有不同的地方,由 Native 中的 send
函式开始,以 android 为例,DartMessenger
的send
方法,在send
方法中,callback 就被转换成了 resposeId,且callback 被储存在 pendingReplies 中,然後呼叫 flutterJNI.dispatchPlatformMessage
,通过 jni 呼叫 DispatchPlatformMessage
函式,传送讯息至 engine 层,由engine 层与Flutter 层进行讯息的处理
最後在PlatformDispatcher
中呼叫 _dispatchPlatformMessage
来传入讯息,并由PlatformMessageResponseCallback
callback 回拨至window.onPlatformMessage
,也就是在 ServicesBinding 中的 defaultBinaryMessenger.handlePlatformMessage
,接收到讯息之後,BinaryMessenger 需要选择合适的 MessageHandler 处理讯息,最後经过 MessageHandler 处理之後会得到 ByteData 型别的处理结果,最终由 callback 将结果回传给 Native
Case01 与 Day23 范例的差异,就是把 js fetch 的语法 extract 成 fu...
今天来介绍一下 Docker 的指令与操作。当我们在执行 Docker Image 时,会将所有的相...
前几天做了很多 AWS 服务使用 CDK 部署的介绍,今天我想来介绍一个满多人都有机会用到的 Blo...
资料分析根据目的和场景的不同,通常会有着不同适合的呈现方式,例如 如果是在学术单位 会偏好比较明确的...
今天就来个说个在新手时期很常遇到,但却不知为什麽会发生的问题 来看一下我们前几天的表单范例,与图上 ...