Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return string from HttpRequest

In Dart I can do:

await HttpRequest.getString(path)

and this will return a string.

I want to create a method that will do the same, but like this:

HttpRequest request = new HttpRequest();
request
    ..open('Get',getPath)
    ..setRequestHeader('Content-Type','application/json')
    ..send('');
...
return responseString;

I can do it using events and futures, but I would like to understand how to do it with async & await specifically.

Edit: This is for the dart:html HttpRequest for browser.

like image 234
Alex Haslam Avatar asked Jan 08 '16 16:01

Alex Haslam


1 Answers

Haven't tried but I guess this is what you're looking for

import 'dart:html';
import 'dart:async';

main() async {
 print(await getString());
}

Future<String> getString() async {
  String getPath = 'https://dartpad.dartlang.org/';
  HttpRequest request = new HttpRequest();
  request
    ..open('Get',getPath)
    ..setRequestHeader('Content-Type','application/json')
    ..send('');

  // request.onReadyStateChange.listen(print);
  await request.onLoadEnd.first;

  return request.responseText;
}
like image 125
Günter Zöchbauer Avatar answered Nov 17 '22 05:11

Günter Zöchbauer