2

After many attempts to get the content of the response in HttpRequest, I failed completely to know or understand why I can't have what I want, and I must mention that I can log and manipulate the response only inside an onReadyStateChange (onLoad and onLoadEnd are giving me the same results!), but I really want that value outside the callback.

Here is the part of code that I'm stuck with

Map responsData;
req=new HttpRequest()
            ..open(method,url)
            ..send(infojson);

req.onReadyStateChange.listen((ProgressEvent e){

  if (req.readyState == HttpRequest.DONE ){

    if(req.status == 200){

      responsData = {'data': req.responseText};
      print("data receaved: ${ req.responseText}");
      //will log {"data":mydata}

    }
    if(req.status == 0){

      responsData = {'data':'No server'};
      print(responsData );
      //will log {"data":No server}

    }  
  }
});
//anything here to get responsData won't work
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Saïd Tahali
  • 189
  • 10

1 Answers1

1

You have to assign an onLoad callback before you call send. I'm not sure what you mean with only inside an onReadyStateChange. Maybe you want to assign the responseText to a variable outside the the callback.

Create a method:

Future<String> send(String method, String url, String infojson) {
  var completer = new Completer<String>();
  // var result;
  req=new HttpRequest()
        ..open(method,url)
        ..onLoad.listen((event) {
          //print('Request complete ${event.target.reponseText}'))
          // result = event.target.responseText;
          completer.complete(event.target.responseText);
        })
        ..send(infojson);
  return completer.future;
}

and call this method like

var result;
send(method, url).then(
  (e) {
    // result = e;
    print('Request complete ${e}'));
  });
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • yes i want to assign the response to a variable outside the callback in order to send the data outside the class, okey i'll try this solution and i'll give u a feedback so soon ,thank you for the assistance it meant a lot! – Saïd Tahali Nov 04 '13 at 00:20
  • I tried your solution it's good but still not what i need it's only gives the block of callback the mobility to use it in other classes but it doesn't allow getting the value of response outside it! please if i'm misunderstanding what you did there let me know! – Saïd Tahali Nov 04 '13 at 00:49
  • I's hard to know what you want to do. I added commented out lines, maybe this is what you want. The callback methods are closures. You can access variables outside the method like in the commented out lines. You can do this without the completer/future in the onLoad() callback or in the then() callback. – Günter Zöchbauer Nov 04 '13 at 06:24