Cequiel Cequiel - 2 years ago 81
Dart Question

Dart: Synchronous post request

I would like to send a synchronous POST request from the client-side. According to the documentation we can use the 'async' named parameter:


var url = "";
request.open("POST", url, async: false);

But the above example throws the following syntax error:

The keywords 'async', 'await', and 'yield' may not be used as identifiers in an asynchronous or generator function.

How can I send a synchronous POST request?

UPDATE (27 May, 20:23)

I found a workaround to solve this problem:

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;

But I don't like the above solution because it doesn't seem elegant enough.

Answer Source

The solution is to use postFormData() instead of send(). For example:

final req = await HttpRequest
    .postFormData(url, {'action': 'delete', 'id': id});
return req.responseText;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download