swift - 如何在 swift setMethodCallHandler 中使用传递的参数 - self?.methodName(result: result)
问题描述
我试图onPressed
通过方法通道将 Flutter 中的函数中的参数发送到 Swift,并将这些参数作为参数传递给被调用的 Swift 方法。
我的任务是创建一个调用用 Swift 编写的控制器的 Flutter UI。我在这里看到过使用platform.invokeMethod
Flutter 中发送的参数的示例,但它们不会setMethodCallHandler
在 Swift 端的方法内部的方法调用中使用这些参数。call.method
如果匹配我发送的内容,我无法弄清楚如何将这些参数包含在我想要调用的方法中。
1.main.dart中的按钮小部件:
RaisedButton(
child: Text('Get a Number'),
onPressed: () => _getNumber(6, 2),
)
2. main.dart中的异步Flutter函数:
Future<void> _getNumber(int number, int times) async {
String numberText;
try {
final int result = await platform.invokeMethod('multiply', <String, dynamic>{
"number": number,
"times": times
});
numberText = "Your number is $result .";
} on PlatformException catch (e) {
numberText = "Failed to get a number: '${e.message}'.";
}
setState(() {
_numberText = numberText;
});}
3.我在appDelegate.swift中的方法调用处理程序:
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let customChannel = FlutterMethodChannel(name: "samples.flutter.dev",
binaryMessenger: controller)
customChannel.setMethodCallHandler({
[weak self] (call: FlutterMethodCall, result: FlutterResult) -> Void in
switch call.method {
case "getBatteryLevel":
self?.receiveBatteryLevel(result: result)
case "multiply":
self?.multiply(result: result)
default:
result(FlutterMethodNotImplemented)
}
4.我处理这个特定乘法的私有函数:
private func multiply(result: FlutterResult) {
// here I want to access the "number" and "times"
// arguments that I passed in from Flutter
result(Int(number * times))
}
由于我对 swift 和 dart 还很陌生,所以我正在努力弄清楚如何导航/使用result: FlutterResult
. 如何更改该参数或访问其属性以使用我传递给 Flutter 中的 onPressed 函数的参数number
和参数?times
解决方案
改变你的multiply
方法开始这样 - 传入call
:
private func multiply(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if let args = call.arguments as? Dictionary<String, Any>,
let number = args["number"] as? Int,
let times = args["times"] as? Int {
// use number and times as required, for example....
result(number * times) // or your syntax
} else {
result(FlutterError.init(code: "bad args", message: nil, details: nil))
}
推荐阅读
- c++ - 如何用 for 循环替换这个 memcpy?
- typescript - 带有类型保护的通用虚假过滤器未正确缩小类型
- html - 我的 HTML 网站的 favicon 未显示
- java - 使用 SwingWorker java 在线程池中等待任务
- java - 哪些问题可能源于覆盖 java.util.HashSets contains() 方法?
- java - 为这个问题寻找合适的同步java代码
- python - 仅向 discord.py 中特定服务器的用户发送欢迎 DM
- google-cloud-platform - 无法通过 SSH/gcloud 连接到默认的 Google 深度学习 VM
- java - 在 Android 中打开另一个活动
- pytorch - 如何检查模型是否在 CUDA 上?