Home > Net >  Sockets and Future Functions in Dart
Sockets and Future Functions in Dart

Time:12-30

  1. Summarize the Problem.

I am trying to write an async function that returns data when a receive is completed from a socket. I am having trouble returning the correct data from my async function. The error I am receiving is that the rtn variable is not set and can be null.

  1. Describe what you've tried.

I've tried writing the async function but haven't been getting the desired result. I tried using the late keyword for the variable rtn but that resulted in a runtime exception that the variable was null.

  1. Show some code.

Below, is the function giving me problems. Any advice or resources would be welcomed. I tried going over the Flutter documentation for async but it wasn't too helpful for me.

What I want is that the network data is returned from this async function.

Future<int> fetchNumVideos() async {

    int rtn;

    Socket.connect(baseStationAddresses[0],
        baseStationPort, timeout: const Duration(seconds: 5)).then((socket) =>
    {
      socket.listen((data) {
        String socketData = String.fromCharCodes(data);

        print("socketData: $socketData");

         rtn = int.parse(socketData);

      },
        onDone: ((){
          socket.destroy();
        })
      ),
    }).catchError((onError) {
      rtn = 0;
    });

    return rtn;
  }

Thank you!

CodePudding user response:

This issue has been solved by pskink's comment.

The solution was to use the Completer class.

  Future<int> fetchNumVideos() async {

    final completer = Completer<int>();

    Socket.connect(baseStationAddresses[0],
        baseStationPort, timeout: const Duration(seconds: 5)).then((socket) =>
    {

      socket.listen((data) {
        String socketData = String.fromCharCodes(data);

        print("socketData: $socketData");

         completer.complete(int.parse(socketData));

      },
        onDone: ((){
          socket.destroy();
        })
      ),
    }).catchError((onError) {
      completer.complete(0);
    });

    return completer.future;
  }

  • Related