赞
踩
MethodChannel 简介 : MethodChannel 通道用于方法调用 ;
一次性通信 : 该方法是一次性通信 , 在 Flutter 中调用在该方法 , 仅能调用一次 Android 方法 ;
MethodChannel 原型 :
/// A named channel for communicating with platform plugins using asynchronous /// method calls. /// /// Method calls are encoded into binary before being sent, and binary results /// received are decoded into Dart values. The [MethodCodec] used must be /// compatible with the one used by the platform plugin. This can be achieved /// by creating a method channel counterpart of this channel on the /// platform side. The Dart type of arguments and results is `dynamic`, /// but only values supported by the specified [MethodCodec] can be used. /// The use of unsupported values should be considered programming errors, and /// will result in exceptions being thrown. The null value is supported /// for all codecs. /// /// The logical identity of the channel is given by its name. Identically named /// channels will interfere with each other's communication. /// /// See: <https://flutter.dev/platform-channels/> class MethodChannel { }
MethodChannel 的构造函数原型如下 :
class MethodChannel { /// Creates a [MethodChannel] with the specified [name]. /// /// The [codec] used will be [StandardMethodCodec], unless otherwise /// specified. /// /// The [name] and [codec] arguments cannot be null. The default [ServicesBinding.defaultBinaryMessenger] /// instance is used if [binaryMessenger] is null. const MethodChannel(this.name, [this.codec = const StandardMethodCodec(), BinaryMessenger? binaryMessenger ]) /// The logical channel on which communication happens, not null. final String name; /// The message codec used by this channel, not null. final MethodCodec codec; }
MethodChannel 构造方法参数说明 :
String name 参数 : Channel 通道名称 , Native 应用端 与 Flutter 中的 Channel 名称 , 必须一致 ;
MethodCodec<T> codec 参数 : 消息编解码器 , 默认类型是 StandardMethodCodec ; Native 应用端 与 Flutter 中的消息编解码器也要保持一致 ;
创建了 MethodChannel 实例对象之后 , 通过调用
@optionalTypeArgs
Future<T?> invokeMethod<T>(String method, [ dynamic arguments ]) {
return _invokeMethod<T>(method, missingOk: false, arguments: arguments);
}
方法 , 调用 Native 端的方法 ;
invokeMethod 方法参数 / 返回值 说明 :
使用流程 :
首先 , 导入 Flutter 与 Native 通信 的 Dart 包 ;
import 'package:flutter/services.dart';
然后 , 定义并实现 MethodChannel 对象实例 ;
static const MethodChannel _methodChannel =
const MethodChannel('MethodChannel');
最后 , 调用 MethodChannel 实例对象的 invokeMethod 方法 ;
String response = await _methodChannel.invokeMethod('send', value);
参考资料 :
重要的专题 :
博客源码下载 :
GitHub 地址 : ( 随博客进度一直更新 , 有可能没有本博客的源码 )
博客源码快照 : https://download.csdn.net/download/han1202012/21670919 ( 本篇博客的源码快照 , 可以找到本博客的源码 )
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。