javascriptflutterdartwebview

How do I pass multiple parameter from JavaScript to Dart through a Flutter WebView plugin JavaScript Channel?


Let's say I have a channel named setPosition. I want it to accept 2 parameters x and y and do something with them. I think I should do setPosition.postMessage(x, y) in JavaScript, but then what do I do under onMessageReceived in Dart?

I have Googled this a few times and found nothing so far.


Solution

  • You have to pass everything as a string, and then extract the values you need in onMessageReceived. For example (without null error handling and conversion to number):

    setPosition.postMessage(JSON.stringify({
      'x': 1,
      'y': 2
    }));
    

    And then in Dart within onMessageReceived:

    onMessageReceived(JavaScriptMessage message) {
        final parameters = jsonDecode(message.message);
        final x = parameters!['x'];
        final y = parameters!['y'];
    }