Home > Mobile >  Function returns before its finished
Function returns before its finished

Time:08-21

I'm trying to implement a socket connection between a python server and a flutter client,

everything works well, but when I want to get the response back the function returns null and then prints the response.

I'm receiving the response but after the function returns.

String  rcev_response()  {
    String response = "";
    
    socket.listen((event) {
      response = utf8.decode(event);
      print(response);
     });
  
    return response;
  }

Any idea what's happening here and how can I fix it?

EDIT: After a little bit of debugging, I found out that socket.listen() doesn't actually stop. so the function returns the value before its assigned

and I added a 1ms delay before the return and now it's working properly.

Timer(Duration(seconds: 1), onceAtTheEndOfTheBatch);

this is still not a solution. any help would be appreciated.

CodePudding user response:

try to add async

Future<String>  rcev_response() async {
   String response = "";

   await socket.listen((event) {
     response = utf8.decode(event);
     print(response);
   });

return response;}

maybe this help you :)

CodePudding user response:

The anonymous function that you are passing to listen is going to be called multiple times with chunks of the response. It's up to you to concatenate them. As you need a string you can use the stream join convenience function.

Future<String> rcev_response() async {
  Socket s = await Socket.connect(ipAddr, port);
  s.add(utf8.encode(request));
  String result = await s.transform(utf8.decoder).join();
  await s.close(); // probably need to close the socket
  return result;
}

This assumes that the server will close the socket when it's finished sending.

  • Related