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.
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?
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.
Dart
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);
}
Dart
String alice = methodCall.arguments['alice'];
bool bob = methodCall.arguments['bob'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With