How to pass functions as arguments from Dart/Flutter to Android native code?

bbozo :

I'd like to create a Java-based SDK that can be invoked from Flutter, the Flutter side needs to plug into the SDK by providing callbacks to be executed at different stages of the processing, ideally something like:

Future<Result> = doPayment(
  amount: 100.00, 
  currency: 'USD', 
  onPasscodeEntry: () => _renderInputBox(), 
  onValidation: () => _doValidation()
);

the processing itself takes some time etc so a Future<PaymentResult> pattern makes sense, the application should react to some points of the processing, so it makes sense to pass in callbacks.

Problems:

  1. how to pass functions to Java code? As far as I can tell all the Java-passable method arguments in Flutter are serializable-ish objects

  2. (less critical/optional) how to return a POJO and handle it in Dart? Judging from the specs I should encode (within Java) the result in a ArrayList/HashMap or as a JSON string and then create the equivalent constructor in Dart that takes in List/Map ? This seems a bit unwieldy, so I'm asking if there's a simpler way, preferably without maintaining a Java & Dart variants of the same object

Günter Zöchbauer :

You can not pass a function.

You can create a map from a function name to a function reference and then pass the function name and look up the function in by name in the map and call it.

You also can't pass a POJO.

You need to serialize it to JSON (or some other supported format) and deserialize it on the other side of the channel. For that you need to have to POJO class implemented in Dart and in Java.

Packages like protobuf or flatbuffer allow to geneerate code for different languages based on an reduced language to specify the data structure.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=153366&siteId=1