【问题标题】:Return string from HttpRequest从 HttpRequest 返回字符串
【发布时间】:2016-04-13 09:13:03
【问题描述】:

在 Dart 中我可以做到:

await HttpRequest.getString(path)

这将返回一个字符串。

我想创建一个可以做同样事情的方法,但是像这样:

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

我可以使用事件和期货来做到这一点,但我想了解如何专门使用 async 和 await 来做到这一点。

编辑: 这是用于浏览器的 dart:html HttpRequest。

【问题讨论】:

  • 想在哪里做?在浏览器上的 JavaScript 中?还是在 Dart 中?
  • 啊,好点子。认为使用 HttpRequest 很明显。但在浏览器中。

标签: dart dart-html dart-async


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!就是这样,或者至少它有效,并向我展示了其他任何事情所需的步骤。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 2021-02-03
  • 2015-04-30
  • 1970-01-01
  • 2017-03-24
  • 2018-11-24
  • 2016-10-27
相关资源
最近更新 更多