Flutter 与 Android/iOS 之间信息交互通过 Platform Channel 进行桥接; Flutter 定义了三种不同的 Channel;但无论是传递方法还是传递事件,其本质上都是数据的传递;
- MethodChannel:用于传递方法调用;
- EventChannel:用于数据流信息通信;
- BasicMessageChannel:用于传递字符串和半结构化的信息;
每种 Channel 均包含三个成员变量;
- name:代表 Channe 唯一标识符,Channel 可以包含多个,但 name 为唯一的;
- messager:代表消息发送与接收的工具 BinaryMessenger;
- codec:代表消息的编解码器
1、MethodChannel:
flutter代码:
// 调用原生方法
static const methodChannel = const MethodChannel('flutter_and_native_101');
static Future<dynamic> invokNative(String method, {Map arguments}) async {
if (arguments == null) {
return await methodChannel.invokeMethod(method);
} else {
return await methodChannel.invokeMethod(method, arguments);
}
}
// 监听原生返回
Future<dynamic> nativeMessageListener() async {
methodChannel.setMethodCallHandler((resultCall) {
MethodCall call = resultCall;
String method = call.method;
Map arguments = call.arguments;
int code = arguments["code"];
String message = arguments["message"];
setState(() {
recive += " code $code message $message and method $method \n";
print(recive);
});
return null;
});
}
// 调用
onPressed: () {
invokNative("test")
..then((result) {
int code = result["code"];
String message = result["message"];
setState(() {
recive = "invokNative 中的回调 code $code message $message ";
});
});
}
android代码:
private void methodChannelFunction() {
mMethodChannel = new MethodChannel(getFlutterView(), "flutter_and_native_101");
//设置监听
mMethodChannel.setMethodCallHandler(
new MethodChannel.MethodCallHandle