4

I am trying to pass arguments from a callback method in Swift to Flutter. This is an example of what I want to achieve, in my native Java code:

   @Override
        public void onRewardRequest(final TJPlacement tjPlacement, final TJActionRequest tjActionRequest, final String itemId, final int quantity) {
            this.registrar.activity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Map<String, Object> arguments = new HashMap<>();
                    arguments.put("requestId", tjActionRequest.getRequestId());
                    arguments.put("token", tjActionRequest.getToken());
                    arguments.put("itemId", itemId);
                    arguments.put("quantity", quantity);
                    channel.invokeMethod("onRewardRequest", arguments);
                }
            });
        }

Edit: I am facing an issue, the argument args is undefined and I'm unsure what is the Swift equivalent of arguments.put() from the Java code above. This is my current implementation:

//Calling my method 'onRewardRequest()' from Dart->Swift
 methodChannel.invokeMethod("onRewardRequest", arguments: args, result: {(r:Any?) -> () in

func placement(_ placement: TJPlacement?, didRequestReward request: TJActionRequest?,itemId: String?,quantity: Int) {
       //How do I call `arguments.put` over here like shown above in the Java code?                           
     }
        })
Arnav
  • 1,404
  • 2
  • 19
  • 38
  • Does this help? https://stackoverflow.com/questions/50187680/flutter-how-to-call-methods-in-dart-portion-of-the-app-from-the-native-platfor/50188557#50188557 Make `args` a dictionary at the Swift end. – Richard Heap Apr 29 '20 at 17:13
  • Hey @RichardHeap, I followed the question you send above, I am still facing some problems could you please give it a look? – Arnav Apr 29 '20 at 17:30
  • https://www.tutorialspoint.com/swift/swift_dictionaries.htm – Richard Heap Apr 29 '20 at 17:33
  • @RichardHeap I understood the dictionaries part, but do I call arguments.put in Swift? – Arnav Apr 29 '20 at 17:41
  • The code at the moment makes no sense. You appear to be trying to make a native->Dart call inside of the handler of a Dart->native call. Can you re-organise it to make clearer what you are trying to do and where you are stuck? – Richard Heap Apr 29 '20 at 18:11
  • Hi, sorry for the mess @RichardHeap, I updated my question. – Arnav Apr 29 '20 at 18:17

1 Answers1

3

It looks like you want to call a Dart method from Swift, passing an argument of a dictionary (will become a Map at the Dart end). Create a dictionary of the relevant type, for example: String->Any, populate it and use that as the arguments parameter.

  var args = [String: Any]()
  args["itemId"] = itemId
  args["quantity"] = quantity
  // todo - add other arg members
  methodChannel.invokeMethod("onRewardRequest", arguments: args)
Richard Heap
  • 48,344
  • 9
  • 130
  • 112