I'm trying to send arguments in an onPressed
function in Flutter through a method channel to Swift, and pass those arguments as parameters to the Swift method that is called.
I've been tasked with creating a Flutter UI that calls on controllers written in Swift. I've seen examples here that utilize arguments sent with the platform.invokeMethod
in Flutter, but they don't use those arguments in a method call inside the setMethodCallHandler
method on the Swift side. I can't figure out how to include those arguments in the method I want to invoke if the call.method
matches what I sent through.
1.The button widget in main.dart:
RaisedButton(
child: Text('Get a Number'),
onPressed: () => _getNumber(6, 2),
)
2. The async Flutter function in main.dart:
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. My method call handler in 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. My private function that handles this specific multiplication:
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))
}
Since I'm pretty new to swift and dart, I am struggling to figure out how to navigate/utilize the result: FlutterResult
. How can I change that parameter or access its properties to use the number
and times
arguments I passed into the onPressed function in Flutter?
Change your multiply
method to start like this - pass call
in:
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With