如何将函数作为参数从Dart / Flutter传递到Android本机代码? [英] How to pass functions as arguments from Dart/Flutter to Android native code?

查看:335
本文介绍了如何将函数作为参数从Dart / Flutter传递到Android本机代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可以从Flutter调用的基于Java的SDK,Flutter端需要通过提供在处理的不同阶段执行的回调来插入SDK,理想情况是:

  Future< Result> = doPayment(
金额:100.00,
货币:'USD',
onPasscodeEntry:()=> _renderInputBox(),
onValidation:()=> _doValidation()
);

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



问题:


  1. 如何将函数传递给Java代码? 到目前为止正如我所知道的,Flutter中所有Java可以通过的方法参数都是可序列化的对象


  2. (不太重要/可选),如何返回POJO并在Dart中处理它?根据规范,我应该在Java中对结果进行编码 ArrayList / HashMap 或作为 JSON 字符串,然后在Dart中创建等效的构造函数,该构造函数接受 List / Map ?这似乎有点笨拙,所以我想问是否有一种更简单的方法,最好不要维护Java&同一对象的Dart变体



解决方案

您无法传递函数。



您可以创建一个从函数名称到函数引用的映射,然后传递函数名称并在映射中按名称查找函数,然后调用它。 / p>

您也无法传递POJO。



您需要将其序列化为JSON(或其他受支持的格式)格式),然后在频道的另一端反序列化。为此,您需要在Dart和Java中实现POJO类。



像protobuf或flatbuffer之类的程序包允许根据一种简化的语言为不同的语言生成代码以指定数据结构。


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

解决方案

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.

这篇关于如何将函数作为参数从Dart / Flutter传递到Android本机代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆