从HttpRequest返回字符串

Ale*_*lam 4 dart dart-html dart-async

在达特我能做到:

await HttpRequest.getString(path)
Run Code Online (Sandbox Code Playgroud)

这将返回一个字符串.

我想创建一个会做同样的方法,但是像这样:

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

我可以使用事件和期货来做到这一点,但我想了解如何使用async&await具体做到这一点.

编辑:这是针对浏览器的dart:html HttpRequest.

Gün*_*uer 5

没试过,但我想这就是你要找的东西

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;
}
Run Code Online (Sandbox Code Playgroud)