Search code examples
fluttersocketsdartstreamfuture

Dart socket listen doesn't wait until done


I would like to do these in a function:
1- connect socket 2- send query 3- listen data 4- return data

but when I tried the socket. listen function doesn't wait even I put await on it. It says it's not a future it's a Stream object but I have no idea about Streams so I'm stuck here. How can I do what I said?

static sendQuery({required String query,args, dimension}) async {
if(args != null)
  args.forEach((element) => query = query.replaceFirst("?", element));

String ip = shared.getData("remote_ip");
int port = shared.getData("remote_port");
String data =  "";
await Socket.connect(ip, port,timeout: Duration(seconds: 5)).then((soket) {
  soket.write(query);
  soket.listen((Uint8List buffer) async {
    String _buffer = String.fromCharCodes(buffer);
    data += _buffer;
  },
  onDone: () {});
});

print("Data has returned. Length of data: ${data.length}");
return data;}

Solution

  • You're awaiting the result of the call to Socket.listen, but that returns a StreamSubscription, not a Future, and you can use await only on Futures.

    You can, however, use StreamSubscription.asFuture to create a Future that will complete when the Stream completes normally or with an error.

    Additionally, it's inconsistent to use both .then() and await. Pick one; using await is usually more straightforward:

    var socket = await Socket.connect(ip, port, timeout: Duration(seconds: 5));
    soket.write(query);
    var subscription = soket.listen((Uint8List buffer) async {
      String _buffer = String.fromCharCodes(buffer);
      data += _buffer;
    });
    await subscription.asFuture<void>();