Nico Rodsevich Nico Rodsevich - 3 months ago 20
Dart Question

Save caller identity in .listen() in dart

I'm making several websockets that will be handled by single annonymous functions:

handleWebSocketCreation(WebSocket socket) {
connections[++current_connections] = socket;
socket.listen((String s) => print("Client $current_connections sent: $s"), onDone: () {
print('Client $current_connections disconnected');
});
}


That obviously doesn't works as expected (it will keep printing the greater the current_connections value it has whichever the socket has sent rather than the actual id of the same)

Any workaround that could output like this?:


Client 3 sent: hello

Client 1 sent: hi, 3!

Client 2 disconnected

etc...

lrn lrn
Answer

You need to capture the value of current_connection in a variable so you can use it later.

handleWebSocketCreation(WebSocket socket) {
  int id = ++current_connections;
  connections[id] = socket;
  socket.listen((String s) { 
    print("Client $id sent: $s"); 
  }, onDone: () {
    print('Client $id disconnected');
  });
}
Comments