10

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?

Jasurbek
  • 2,946
  • 3
  • 20
  • 37
kimusan
  • 495
  • 5
  • 13
  • Possible duplicate of [Flutter: How to call methods in Dart portion of the app, from the native platform using MethodChannel?](https://stackoverflow.com/questions/50187680/flutter-how-to-call-methods-in-dart-portion-of-the-app-from-the-native-platfor) – Richard Heap Jul 03 '19 at 10:39

1 Answers1

20

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'];
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
  • Hi, That part I understand as this is what the examples show. What I am not sure about is how I achieve the same but from java to dart. I need bi-directional communication as my native code will need to do periodic "callbacks" to the upper layers (dart) of my app. – kimusan Jul 03 '19 at 08:10
  • Updated answer. – Richard Heap Jul 03 '19 at 10:46
  • @RichardHeap Where did the methodCall.arguments come from – Asbah Riyas May 27 '20 at 03:13
  • @AsbahRiyas see: https://stackoverflow.com/questions/50187680/flutter-how-to-call-methods-in-dart-portion-of-the-app-from-the-native-platfor/50188557#50188557 – Richard Heap May 28 '20 at 01:11
  • 2
    It should be `result.success(arguments);` on the java message to dart – Patrick Waweru Apr 09 '21 at 13:02