首页 > 解决方案 > 如何在 swift setMethodCallHandler 中使用传递的参数 - self?.methodName(result: result)

问题描述

我试图onPressed通过方法通道将 Flutter 中的函数中的参数发送到 Swift,并将这些参数作为参数传递给被调用的 Swift 方法。

我的任务是创建一个调用用 Swift 编写的控制器的 Flutter UI。我在这里看到过使用platform.invokeMethodFlutter 中发送的参数的示例,但它们不会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

标签: swiftasynchronousflutterdart

解决方案


改变你的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))
  }

推荐阅读