flutter 与 Ios 原生通讯
- MethodChannel
flutter
调用 ios
原生方法,使用 MethodChannel
用于传递方法调用(method invocation)通常用来调用 native 中某个方法
native端
// 注册测试插件方法
func testPlugin(message: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(name: "plugin_apple", binaryMessenger: message)
channel.setMethodCallHandler {
(call: FlutterMethodCall, result: @escaping FlutterResult) in
if (call.method == "apple_one") {
result(["result": "success", "code": 200] as [String : Any])
}
if (call.method == "apple_two") {
result(["result": "success", "code": 404] as [String : Any])
}
}
}
在 AppDelegate 中调用:
// ... code
// 注册新测试方法
// 挂载到rootview上
let messager : FlutterBinaryMessenger = window?.rootViewController as!FlutterBinaryMessenger
testPlugin(message: messager);
// ... code
Flutter端
// 调用 apple_one 方法
Future<void> appleOne() async {
MethodChannel _channel = const MethodChannel("plugin_apple");
final result = await _channel.invokeMethod("apple_one");
Map map = result as LinkedHashMap<Object?, Object?>;
print("result: ${map["result"]}");
print("code: ${map["code"]}");
}
// 调用 apple_two 方法
Future<void> appleTwo() async {
MethodChannel _channel = const MethodChannel("plugin_apple");
final result = await _channel.invokeMethod("apple_two");
Map map = result as LinkedHashMap<Object?, Object?>;
print("result: ${map["result"]}");
print("code: ${map["code"]}");
}
/// 布局
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
appleOne();
},
child: const Text("调用方法 apple_one"),
),
const SizedBox(
height: 10,
),
GestureDetector(
onTap: () {
appleTwo();
},
child: const Text("调用 apple_two"),
)
],
),
)
预览
调用会在控制台输出测试