How to add channel to send message in flutter_js

196 Views Asked by At

I am trying to pass a message from Javascript to Flutter using package flutter_js but it seems like it's not working cuz it shows No Channel " " registered

below is my code

Future<dynamic> getObjectName(JavascriptRuntime jsRuntime) async {
  final completer = Completer();

  JsEvalResult jsEvalResult = jsRuntime.evaluate("""
  const Person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue"
  };

  // const personJson = JSON.stringify(Person);
  sendMessage('passJson2Dart', JSON.stringify(Person));
  """);

  jsRuntime.onMessage('passJson2Dart', (args) {
    print("test argument" + args);
    Map<String, dynamic> person = json.decode(args);
    print("test decode");
    print(person);
    return person;
  });

  // jsRuntime.onMessage('passJson2Dart', (args) {
  //   Map<String, dynamic> person = json.decode(args);
  //   completer.complete(person);
  // });

  // return completer.future;
}

Can I know how to add or register channel inside the JavascriptRuntime object

1

There are 1 best solutions below

0
On

The way I have it setup in my project is the following:

Create the callbackChannel and then reference the callbackChannel in your function.

final String _callbackChannel = 'callback${const ShortUuid().generate()}';


void addCallbackHandler(JavaScriptCallbackHandler handler) {
  _callbackHandlers.add(handler);
  <enter code here>
  if (!_onMessageAdded) {
    _runtime.onMessage(_callbackChannel, _onMessage);
    _onMessageAdded = true;
  }
}