簡介
? BinaryMessenger是Platform端與Flutter端通信的工具,其通信使用的消息格式為二進制格式數(shù)據(jù)。當我們初始化一個Channel,并向該Channel注冊處理消息的Handler時,實際上會生成一個與之對應的BinaryMessageHandler,并以channel name為key,注冊到BinaryMessenger中。當Flutter端發(fā)送消息到BinaryMessenger時,BinaryMessenger會根據(jù)其入?yún)hannel找到對應的BinaryMessageHandler,并交由其處理。
Binarymessenger在Android端是一個接口,其具體實現(xiàn)為FlutterNativeView。而其在iOS端是一個協(xié)議,名稱為FlutterBinaryMessenger,F(xiàn)lutterViewController遵循了它。
原理
參考閑魚技術(shù)出品
深入理解Flutter Platform Channel
應用
在Native側(cè),創(chuàng)建一個methodChannel通道,用于調(diào)用flutter側(cè)方法,或者flutter側(cè)調(diào)用Native側(cè)方法,并提供callback。
iOS側(cè):
Objective-C
FlutterMethodChannel* methodChannel = [FlutterMethodChannel
methodChannelWithName:@"MethodChannelName"
binaryMessenger:[GMFlutterViewManager shareInstance].flutterVC];
[methodChannel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult _Nonnull result) {
if ([@"foo" isEqualToString:call.method]) {
result(some data);
} else {
result(FlutterMethodNotImplemented);
}
}];
關(guān)鍵詞:
channelName:channel唯一標識,Native側(cè)和flutter側(cè)保持名稱一致。
binaryMessenger:channel Context。
handle:typedef void (^FlutterMethodCallHandler)(FlutterMethodCall* call, FlutterResult result);
FlutterMethodCall:包含method
(方法名)和arguments
(參數(shù))的對象,管理方法對象
FlutterResult:typedef void (^FlutterResult)(id _Nullable result);
Android側(cè):
new MethodChannel(BinaryMessenger, "MethodChannelName").setMethodCallHandler(
(call, result) -> {
if (call.method.equals("foo")) {
result.success(some data);
} else {
result.notImplemented();
}
});
關(guān)鍵詞:
binaryMessenger:傳入flutter Context,及FlutterNativeView。
flutter側(cè):
dart
static const MethodChannel methodChannel =
MethodChannel('MethodChannelName');
Future<void> _foo() async {
Uint8List imageData;
try {
final result = await methodChannel.invokeMethod('foo');
data = result;
} on PlatformException {
data = null;
}
setState(() {
_data = data;
});
}
關(guān)鍵詞:
Future、async:異步操作套裝
Future-官方文檔
setState:觸發(fā)重繪當前節(jié)點,以更新UI。