Call Flutter from native iOS and get value back using Pigeon FlutterApi

978 Views Asked by At

I'm using Pigeon library to connect Flutter and native platform code, in particular iOS with Swift.

I want to call a flutter function from Swift and get a value back, all synchronously.

The function on flutter is defined like this:

@FlutterApi()
abstract class MyFlutterApi {
    String? didSyncFunctionCalled();
}

Here the Swift code:

let flutterApi: MyFlutterApi?

public func callSyncFunction() -> String? {
    flutterApi?.didSyncFunctionCalled(completion: { (value: String?, error: Error?) in
        return value
    })
}

As you can see the function returns a string (nullable) and I need that string from flutter.

This implementation is incorrect. I get an error from XCode on the line of return value -> Cannot convert value of type 'String?' to closure result type 'Void'

From what I understood, Pigeon always generates code with completion closure with error and eventually a value to return.

This is the solution I don't want to use:

public func callSyncFunction(completion: @escaping (String?) -> Void) {
    flutterApi?.didSyncFunctionCalled(completion: { (value: String?, error: Error?) in
        completion(value)
    })
}

Is there a method to define functions that can be used like this in native code?

public func callSyncFunction() -> String? {
    let value: String? = flutterApi?.didSyncFunctionCalled()
    return value
}

1

There are 1 best solutions below

0
Zdeněk Vaníček On

You only return data synchronously the requests from the API is async. It is all built on MethodChannels so the async functionality did not dissapear its more of wrapped up.