Sudhi
Sudhi

Reputation: 229

Dart HTTPClient Response query

I would like to make the below functionality synchronous. The "onDataLoaded" needs to be called once the stream has been read completely. Please suggest what changes needs to be done.

String JsonContent="";

new HttpClient().getUrl(Uri.parse(uri))
  .then((HttpClientRequest request) 
   {
      request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);          
      return request.close();
   })
  .then((HttpClientResponse response) 
   {   
      response.transform(UTF8.decoder).listen((contents) {
        JsonContent = contents.toString();  
        print(JsonContent);
        //onDataLoaded(JsonContent); 
      });          
   });

Upvotes: 2

Views: 1601

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657909

this should work

import 'dart:io';
import 'dart:convert' show UTF8;

void main(args) {
String JsonContent="";

new HttpClient().getUrl(Uri.parse(uri))
  .then((HttpClientRequest request)
   {
      request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
      return request.close();
   })
  .then((HttpClientResponse response)
   {
      response.transform(UTF8.decoder).listen((contents) {
        JsonContent = contents.toString();
        print(JsonContent);
        //onDataLoaded(JsonContent);
      }, onDone: () => onDataLoaded(JsonContent));
   });

}

void onDataLoaded(String jsonContent) {
  print(jsonContent);
}

Upvotes: 3

Related Questions