问题描述
我有一个flutter项目(插件),该项目也使用一些本机Java代码.要在dart和Java之间进行通信,请使用MethodChannel.invokeMethod
.这对于Java的dart来说非常有效,我可以在Java中使用call.argument("name")
提取命名参数.但是,另一种方法让我有些头疼,因为我需要通过方法调用将可变数量的参数传递给dart,但是invokeMethod仅将"Object
"作为参数.
I have a flutter project (plugin) that uses some native java code as well. To communicate between dart and java I use the MethodChannel.invokeMethod
. This works very nicely from dart for java and I can pull out the named arguments with call.argument("name")
in java. The other way is, however, giving me a bit of headache as I need to pass a variable number of arguments to dart with my method call, but invokeMethod only takes "Object
" as an argument.
我已经看到它只适用于单个参数(例如字符串或整数),但是我似乎找不到找到针对多个参数实现它的好方法.
I have seen it work with just the single argument like a string or int, but I cannot seem to find a good way to implement it for multiple arguments.
我本来希望可以将某种列表对象类型作为invokeMethod的参数传递,但是我无法在任何地方找到它.
I would have expected that there was some sort of list object type that I could pass as an argument for invokeMethod but I have not been able to find it anywhere.
任何人都可以提示如何做到最好吗?
Can any of you give a hint on how to best do this?
推荐答案
您必须将Map<String, dynamic>
作为单个对象传递. (请注意,每个动态参数都必须是允许的数据类型.)这在Java端显示为HashMap
. Java端有有用的getter函数来访问哈希映射成员.
You have to pass a Map<String, dynamic>
as the single object. (Note that each of the dynamics must be one of the allowed data types.) This appears at the Java end as a HashMap
. There are useful getter functions at the Java end to access the hash map members.
飞镖
static void foo(String bar, bool baz) {
_channel.invokeMethod('foo', <String, dynamic>{
'bar': bar,
'baz': baz,
});
}
Java
String bar = call.argument("bar"); // .argument returns the correct type
boolean baz = call.argument("baz"); // for the assignment
使用此,您可以实现相反的方向,例如:
Using this answer for the full outline, you can achieve the opposite direction like:
Java
static void charlie(String alice, boolean bob) {
HashMap<String, Object> arguments = new HashMap<>();
arguments.put("alice", alice);
arguments.put("bob", bob);
channel.invokeMethod("charlie", arguments);
}
飞镖
String alice = methodCall.arguments['alice'];
bool bob = methodCall.arguments['bob'];
这篇关于我如何最好地使用flutters的Java版本MethodChannel.invokeMenthod给出多个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!