我在这里创建了一个工作示例
https://github.com/theamorn/flutter-template
在这个文件中,我有 3 种连接到 Native SDK 的方式
- 立即调用 Native 并返回值
- 调用 Native 并传递给函数并从该函数返回
- 调用 Native 并等待委托回调,以便我们可以回调到 Flutter
首先你在 iOS 中添加 Flutter Channel
https://github.com/theamorn/flutter-template/blob/main/ios/Runner/AppDelegate.swift
private func initFlutterChannel() {
// com.theamorn.flutter can change to whatever you want, just have to be the same between Flutter and iOS and unique ‘domain prefix. just com.theamorn is not enough
if let controller = window?.rootViewController as? FlutterViewController {
let channel = FlutterMethodChannel(
name: methodChannel,
binaryMessenger: controller.binaryMessenger)
channel.setMethodCallHandler({ [weak self] (
call: FlutterMethodCall,
result: @escaping FlutterResult) -> Void in
switch call.method {
case "methodNameOne":
if let data = call.arguments as? String {
self?.callNativeSDK(data)
} else {
result(FlutterMethodNotImplemented)
}
case "deviceHasPasscode":
result(self?.isDeviceHasPasscode)
case "returnValue":
if let data = call.arguments as? String {
self?.returnValueSDK(result: result, id: data)
} else {
result(FlutterMethodNotImplemented)
}
default:
result(FlutterMethodNotImplemented)
}
})
}
}
methodNameOne 用于调用 Native 函数,其名称应在 Flutter 中保持一致
private func callNativeSDK(_ id: String) {
// You can put any Native SDK in here, if the result return from Delegate
let sdk = ThirdPartySDK(delegate: self, id: id)
sdk.start()
}
private func returnValueSDK(result: FlutterResult, id: String) {
// You can call any SDK in here if the result return immediately
let sdk = ThirdPartySDK(delegate: self, id: id)
return result(sdk.process())
}
使用这个从 Flutter 调用
https://github.com/theamorn/flutter-template/blob/main/lib/main.dart
final channel = MethodChannel('com.theamorn.flutter');
try {
await channel.invokeMethod('methodNameOne', "12345");
} on PlatformException catch (e) {
debugPrint("==== Failed to get data '${e.message}' ====");
}
从 Native 回调到 Flutter,我在 mocking SDK 的 Delegate 中调用这个函数
extension AppDelegate: ThirdPartySDKDelegate {
func onFinish(value: String) {
// You can send anything into arguments, String, Boolean, or even Dictionary
// Send data back to Flutter
if let controller = self.window?.rootViewController as? FlutterViewController {
let channel = FlutterMethodChannel(
name: methodChannel,
binaryMessenger: controller.binaryMessenger)
channel.invokeMethod("methodNameTwoFromSDK", arguments: value)
}
}
}
等待来自 Native 的值
_waitingDataFromNative() async {
channel.setMethodCallHandler((call) async {
// Receive data from Native
switch (call.method) {
case "methodNameTwoFromSDK":
_nativeValue = call.arguments;
setState(() {});
break;
default:
break;
}
});
}
您在 iOS 中看到该方法名称,Flutter 需要完全相同,否则它们无法看到彼此。