简体   繁体   English

如何将函数作为参数从 Dart/Flutter 传递给 Android 本机代码?

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

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:我想创建一个可以从 Flutter 调用的基于 Java 的 SDK,Flutter 端需要通过提供在处理的不同阶段执行的回调来插入 SDK,理想情况下是这样的:

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.处理本身需要一些时间等,因此Future<PaymentResult>模式是有意义的,应用程序应该对处理的某些点做出反应,因此传入回调是有意义的。

Problems:问题:

  1. how to pass functions to Java code?如何将函数传递给Java代码? As far as I can tell all the Java-passable method arguments in Flutter are serializable-ish objects 据我所知 Flutter 中所有 Java 可传递的方法参数都是可序列化的对象

  2. (less critical/optional) how to return a POJO and handle it in Dart? (不太重要/可选)如何返回 POJO 并在 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 ?规范来看,我应该(在 Java 中)将结果编码为ArrayList / HashMap或作为JSON字符串,然后在 Dart 中创建等效的构造函数,该构造函数接受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这似乎有点笨拙,所以我问是否有更简单的方法,最好不要维护同一对象的 Java 和 Dart 变体

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.你也不能通过 POJO。

You need to serialize it to JSON (or some other supported format) and deserialize it on the other side of the channel.您需要将其序列化为 JSON(或其他支持的格式)并在通道的另一端反序列化。 For that you need to have to POJO class implemented in Dart and in Java.为此,您需要在 Dart 和 Java 中实现 POJO 类。

Packages like protobuf or flatbuffer allow to geneerate code for different languages based on an reduced language to specify the data structure. protobuf 或 flatbuffer 等包允许基于简化的语言为不同的语言生成代码以指定数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM