Flutter-channel详解

简介

channel

​ BinaryMessenger是Platform端与Flutter端通信的工具,其通信使用的消息格式为二进制格式数据。当我们初始化一个Channel,并向该Channel注册处理消息的Handler时,实际上会生成一个与之对应的BinaryMessageHandler,并以channel name为key,注册到BinaryMessenger中。当Flutter端发送消息到BinaryMessenger时,BinaryMessenger会根据其入参channel找到对应的BinaryMessageHandler,并交由其处理。

Binarymessenger在Android端是一个接口,其具体实现为FlutterNativeView。而其在iOS端是一个协议,名称为FlutterBinaryMessenger,FlutterViewController遵循了它。

原理

参考闲鱼技术出品
深入理解Flutter Platform Channel

应用

在Native侧,创建一个methodChannel通道,用于调用flutter侧方法,或者flutter侧调用Native侧方法,并提供callback。

iOS侧:

    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);
        }
    }];

关键词:
channelName:channel唯一标识,Native侧和flutter侧保持名称一致。
binaryMessenger:channel Context。
handle:typedef void (^FlutterMethodCallHandler)(FlutterMethodCall* call, FlutterResult result);
FlutterMethodCall:包含method(方法名)和arguments(参数)的对象,管理方法对象
FlutterResult:typedef void (^FlutterResult)(id _Nullable result);

Android侧:

        new MethodChannel(BinaryMessenger, "MethodChannelName").setMethodCallHandler(
                (call, result) -> {
                    if (call.method.equals("foo")) {
                        result.success(some data);
                    } else {
                        result.notImplemented();
                    }
                });

关键词:
binaryMessenger:传入flutter Context,及FlutterNativeView。

flutter侧:

dart
  static const MethodChannel methodChannel =
      MethodChannel('MethodChannelName');

  Future _foo() async {
    Uint8List imageData;
    try {
      final result = await methodChannel.invokeMethod('foo');
      data = result;
    } on PlatformException {
      data = null;
    }
    setState(() {
      _data = data;
    });
  }

关键词:
Future、async:异步操作套装
Future-官方文档
setState:触发重绘当前节点,以更新UI。

你可能感兴趣的:(Flutter-channel详解)