Flutter - channel

@、BasicMessageChannel<T>

BasicMessageChannel<T>

  Future<T> send(T message) async

  void setMessageHandler(Future<T>handler(T message))

  

MessageCodec<T>:

  ByteData encodeMessage(T message);

  T decodeMessage(ByteData message);

BinaryMessenger

  Future<void> handlePlatformMessage(String channel, ByteData data, ui.PlatformMessageResponseCallback callback);

    处理platform的调用,具体调用channel对应的setMessageHandler设置的handler

  Future<ByteData> send(String channel, ByteData message);

    调用platform

  void setMessageHandler(String channel, MessageHandler handler);

    设置处理platform调用的处理器

 

@、MethodChannel

MethodChannel

  Future<T> invokeMethod<T>(String method, [ dynamic arguments ])

    内部调用的是binaryMessenger.send

  void setMethodCallHandler(Future<dynamic> handler(MethodCall call))

     内部调用的是binaryMessenger.setMessageHandler

 

MethodCodec

  StandardMethodCodec

    内部使用StandardMessageCodec,对MethodCall的method和arguments两个参数进行处理

  ByteData encodeMethodCall(MethodCall methodCall);

    调用平台时将MethodCall转ByteData

  MethodCall decodeMethodCall(ByteData methodCall);

    被平台调用时将ByteData转MethodCall

  dynamic decodeEnvelope(ByteData envelope);
    将调用平台方法返回的数据转成对象

  ByteData encodeSuccessEnvelope(dynamic result);
    被平台调用成功,将结果转成ByteData
 
  ByteData encodeErrorEnvelope({ @required String code, String message, dynamic details });
    被平台调用失败,将错误信息转成ByteData

MethodCall

  finalString method;

  finaldynamic arguments;

 

BinaryMessenger

 

 

@、EventChannel

EventChannel

  Stream<dynamic>receiveBroadcastStream([ dynamic arguments ])  

  里面是通过MethodChannel调用listen和cancel方法。

MethodCodec

 

BinaryMessenger

 

@、总结

flutter 调用平台:XXXChannel ----codec.encodeXXX将dart对象转成ByteData--->BinaryMessenger.send----------------->android/ios... ------codec.decodeXXX将平台返回的ByteData转成dart对象

平台调用flutter:

  首先:XXXChannel.setMessageHandler(handler);

  然后:android/ios... ----->BinaryMessenger.handlePlatformMessage--------->handler-----codec将对象ByteData转成dart对象---->成功返回结果或者失败返回错误信息 

 

 

 

 

 

 
Stream<dynamic> receiveBroadcastStream([ dynamic arguments ])
posted @ 2020-10-07 12:30  liDB  阅读(277)  评论(0编辑  收藏  举报