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
有帮助吗?

解决方案

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}'));
  });
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top