flutterdartblocflutter-cubit

Unable to print value from async and await


I am trying to print and return value outside stream block using async and await but i am not able to print it outside.

Please help.

Here is the below code

getMarkets() async {
  //IOWebSocketChannel.connect('wsxxxxx');

  var response;
  var channel = IOWebSocketChannel.connect(
    Uri.parse('xxxx'),
  );

  channel.sink.add(
      '{"xxx":"brief", "xxx": "basic"}');


   response=await channel.stream.listen(
        (data) {
          response =data;
         //here it is printing
          print('--->>>respomseee'+response);
    },
    onError: (error) => print(error),
  );


   //unable to print here or value response cannot be printed
  print('--->>>respomseee111'+response);

 // return response.map((item) => item.toMap());


   response;
}

Solution

  • I think instead of

    response=await channel.stream.listen(
        (data) {
          response =data;
         //here it is printing
          print('--->>>respomseee'+response);
      },
      onError: (error) => print(error),
    );
    

    you simply would want to do

    response = await channel.stream.first;