Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dartlang: How to implemet a callback method

Tags:

callback

dart

I have a class in a library which has the method 'onMessage' that is executed when an event occurs. OnMessage needs to call a 'callback' method belonging to a class in the main application when it executes. I assumed that this would be done through the constructor but I can't figure out how it's implemented.

EDIT

In this version I get one warning in main.dart when I try to create an instance, wss, of WebsocketService.

 // in library class - no warnings

 Object returnResults;

 WebsocketService(Object callback()) {
   returnResults = callback;
 }


 void onMessage(data) {
   var json = JSON.decode(data);
   var echoFromServer = json['response'];
   print("Received message: $echoFromServer");
   returnResults(echoFromServer); // declared 'incoming' in main.dart
 }




 // +++  in main.dart ++++++++
  WebsocketService wss;

  class TestAsynchWS {

    TestAsynchWS() {  // *** Dart Editor warning here
    // 0 positional arguments expected but 1 found
      wss = new WebsocketService(incoming);
    }

 void incoming(echoFromServer) {
 // code
 }
like image 359
Nate Lockwood Avatar asked Oct 02 '22 07:10

Nate Lockwood


1 Answers

Assuming returnResults can be set in the library you can use :

returnResults = incoming;
like image 81
Alexandre Ardhuin Avatar answered Oct 04 '22 17:10

Alexandre Ardhuin