'How to prevent socket.listen getting called asynchronously in dart

Question I am working on a flutter project that uses dart sockets to transfer files from a logger device to the app. I have successfully done this using the socket.onListen method and the socket.write command. In the socket.listen, I write the data into a file and name it. However, if I loop through like 100 times and do a socket.write('command $i'), the onListen does not get call respectively for each file and I believe the files end up getting clumped up. I am wondering if there is a way to make sure each socket.write command gets its on call to socket.listen call. I have looked through at least 50 stack overflow questions and nothing is working for me. Here is my code

int count = 0;
sock = await Socket.connect('192.168.4.1', 25443);

sock.listen((Uint8List data) async {
    print('Data at $count' + data.toString());
    File f = await _localFile(count);
    f.writeAsBytes(data);
});

for(int i =0; i < fileSize; i++){
   sock.write('transfer $i');
   count++;
}

Output Data at 0[19, 3, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 12, 0, 0, 0, 25, 0, 0, 0, 6, 0, 0, 0, 119, 105, 98, 108, 45, 49, 11, 0, 0, 0, 85, 83, 67, 71, 67, 45, 72, 101, 97, 108, 121, 13, 0, 0, 0, 17, 0, 0, 0, 5, 0, 0, 0, 100, 101, 100, 117, 112, 4, 0, 0, 0, 78, 111, 110, 101, 14, 0, 0, 0, 185, 2, 0, 0, 181, 2, 0, 0, 123, 32, 34, 112, 108, 97, 116, 102, 111, 114, 109, 34, 58, 32, 123, 32, 34, 117, 110, 105, 113, 117, 101, 73, 68, 34, 58, 32, 34, 119, 105, 98, 108, 45, 49, 34, 44, 32, 34, 116, 121, 112, 101, 34, 58, 32, 34, 83, 104, 105, 112, 34, 44, 32, 34, 110, 97, 109, 101, 34, 58, 32, 34, 85, 83, 67, 71, 67, 32, 72, 101, 97, 108, 121, 34, 44, 32, 34, 108, 101, 110, 103, 116, 104, 34, 58, 32, 49, 50, 56, 44, 32, 34, 108, 101, 110, 103, 116, 104, 85, 110, 105, 116, 79, 102, 77, 101, 97, 115, 117, 114, 101, 34, 58, 32, 34, 109, 101, 116, 114, 101, 34, 44, 32, 34, 73, 68, 84, 121, 112, 101, 34, 58, 32, 34, 73, 77, 79, 34, 44, 32, 34, 73, 68, 78, 117, 109, 98, 101, 114, 3

It ends there, it does not go onto the other files.

Is there something I am missing? I am open to other ideas to attack this problem as well.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source