How to ‘put’ arguments from Swift native code to Flutter

Tags: , , , ,



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?                           
     }
        })

Answer

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)


Source: stackoverflow