Dart:同步 post 请求

Dart: Synchronous post request

我想从客户端发送同步 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;
}

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

这是此命名参数的一个已知问题 https://github.com/dart-lang/sdk/issues/24637

解决方案是使用 postFormData() 而不是 send()。例如:

final req = await HttpRequest
    .postFormData(url, {'action': 'delete', 'id': id});
return req.responseText;
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"