Return string from HttpRequest

Issue

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.

Solution

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;
}

Answered By – Günter Zöchbauer

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *