Dart:同步发布请求

时间:2016-05-27 17:53:16

标签: dart client httprequest synchronous

我想从客户端发送同步POST请求。根据文档,我们可以使用'async'命名参数:

https://www.dartlang.org/articles/json-web-service/#saving-objects-on-the-server

var url = "http://127.0.0.1:8080/programming-languages";
request.open("POST", url, async: false);

但是上面的示例引发了以下语法错误:

关键字'async','await'和'yield'不能用作异步或生成器函数中的标识符。

如何发送同步POST请求?

更新(5月27日,20:23)

我找到了解决此问题的解决方法:

Future<String> deleteItem(String id) async {
    final req = new HttpRequest()
      ..open('POST', 'server/controller.php')
      ..send({'action': 'delete', 'id': id});
    // wait until the request have been completed
    await req.onLoadEnd.first;
    // oh yes
    return req.responseText;
}

但我不喜欢上述解决方案,因为它看起来不够优雅。

3 个答案:

答案 0 :(得分:0)

这是此命名参数https://github.com/dart-lang/sdk/issues/24637

的已知问题

答案 1 :(得分:0)

解决方案是使用postFormData()代替send()。例如:

final req = await HttpRequest
    .postFormData(url, {'action': 'delete', 'id': id});
return req.responseText;

答案 2 :(得分:0)

Future<String> deleteItem(String id) async {
final req = new HttpRequest()
  ..open('POST', 'server/controller.php')
  ..send({'action': 'delete', 'id': id});
// wait until the request have been completed
await req.onLoadEnd.first;
// oh yes
return req.responseText;

}

这个是重点,有时你需要“PUT”或“DELETE”