Messaging
如何在框架和平台代码之间传递消息?
ServicesBinding.initInstances设置全局消息控制器 (Window.onPlatformMessage) 给ServicesBinding.defaultBinaryMessenger. This instance processes messages from the platform (viaBinaryMessenger.handlePlatformMessage) and allows other framework code to register message handlers (viaBinaryMessenger.setMessageHandler). Handlers subscribe to a channel (an identifier used to multiplex the single engine callback) using an identifier shared by the framework and the platform.
What are the building blocks of messaging?
BinaryMessengermultiplexes the global message handler via channel names, supporting handler registration and bidirectional binary messaging. Sending a message produces a future that resolves to the raw response.MessageCodecdefines an interface to encode and decode byte data (MessageCodec.encodeMessage,MessageCodec.decodeMessage). A cross-platform binary codec is available (StandardMessageCodec) as well as a JSON-based codec (JSONMessageCodec). The platform must implement a corresponding codec natively.MethodCodecis analogous toMessageCodec(but otherwise independent) encoding and decodingMethodCallinstances that wrap a method name and a dynamic list of arguments. Method-based codecs pack and unpack results into envelopes to distinguish success and error outcomes.BasicMessageChannelprovides a thin wrapper aroundBinaryMessagerthat uses the provided codec to encode and decode messages to and from raw byte data.MethodChannelprovides a thin wrapper aroundBinaryMessagerthat uses the provided method codec to encode and decode method invocations. Responses to incoming invocations are packed into envelopes indicating outcome; similarly, results from outgoing invocations are unpacked from their encoded envelope. These are returned as futures.Success envelopes are unpacked and the result returned.
Error envelopes throw a
PlatformException.Unrecognized methods throw a
MissingPluginException(except when using anOptionalMethodChannel).
EventChannelis a helper that exposes a remote stream as a local stream. The initial subscription is handled by invoking a remote method calledlisten(viaMethodChannel.invokeMethod) which causes the platform to begin emitting a stream of envelope-encoded items. A top-level handler is installed (viaServicesBinding.defaultBinaryMessenger.setMessageHandler) to unpack and forward items to an output stream in the framework. If the stream ends (for any reason), a remote method calledcancelis invoked and the global handler cleared.SystemChannelsis a singleton instance that provides references to messaging channels that are essential to the framework (SystemChannels.system,SystemChannels.keyEvent, etc.).
Last updated
Was this helpful?