MethodChannel
是Flutter
与原生交互的一种办法,此种办法传递的是办法,能够双向传递,能够带着参数,双向传递都能够有回来值
Flutter
给原生端发送音讯
-
Flutter
端代码装备
final methodChannel = const MethodChannel('test_method_channel');
Future<void> sendMessageFromMethodChannel() async {
final result = await methodChannel.invokeMethod("method_one");
print(result);
}
界说发送音讯 MethodChannel
生成对应的channel
,需要指定channel
的name
发送音讯运用的是:invokeMethod
指定办法名,也能够带参数,有回来值
- 原生端代码装备
先界说一个MethodChannelManager
管理类
var channel: FlutterMethodChannel
init(messager: FlutterBinaryMessenger) {
channel = FlutterMethodChannel(name: "test_method_channel", binaryMessenger: messager)
channel.setMethodCallHandler { (call , result) in
print("接纳到了来自Flutter发送的办法\(call.method)")
result("我是原生回来给Flutter的音讯")
}
}
界说好channel
,注册办法 setMethodCallHandler
在AppDelegate
进口函数处需要初始化
let messager = window.rootViewController as! FlutterBinaryMessenger
MethodChannelManager(messager: messager)
运转项目后,点击触发事情,打印如下:
原生(iOS为例)
给Flutter
发送音讯
-
iOS
原生端装备
var channel: FlutterMethodChannel
init(messager: FlutterBinaryMessenger) {
channel = FlutterMethodChannel(name: "test_method_channel", binaryMessenger: messager)
channel.setMethodCallHandler { (call , result) in
print("接纳到了来自Flutter发送的办法\(call.method)")
result("我是原生回来给Flutter的音讯")
self.startTimer()
}
}
func startTimer() {
Timer.scheduledTimer(timeInterval: TimeInterval(2), target: self, selector: #selector(sendMessageToFlutter), userInfo: nil, repeats: false)
}
@objc func sendMessageToFlutter() {
channel.invokeMethod("ios_method", arguments: "我是原生主动发送过来的") {(result) in
print(result)
}
}
原生端发送音讯也是调用 invokeMethod
,也能够以闭包方式接纳到Flutter
端的回来值
-
Flutter
端装备
Future<void> setMethodChannelCallHandler() async {
methodChannel.setMethodCallHandler((call) async {
print('Flutter收到了原生端的办法:${call.method}, 传参为:${call.arguments} ---- call: $call');
return Future.value('我是Flutter回传给原生端的数据');
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
setMethodChannelCallHandler();
}
Flutter
中装备的setMethodChannelCallHandler
也能够给原生回传数据,直接回来一个 Future
即可
运转打印结果如下: