Home > Enterprise >  Why is http.post not an async function
Why is http.post not an async function

Time:12-31

I'm working on an application in dart. I use the http package. I copied the example code from the documentation:

var url = Uri.parse('https://example.com/whatsit/create');
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
 

And get this error:

Error: The await expression can only be used in an async function.

I have no idea why this doesn't work. Its their own example.

CodePudding user response:

You need to make sure your code is written inside a Future function like so:

void yourFunction() async {
  var url = Uri.parse('https://example.com/whatsit/create');
  var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
  print('Response status: ${response.statusCode}');
  print('Response body: ${response.body}');
}

Or if you can't do that, use .then() syntax

var url = Uri.parse('https://example.com/whatsit/create');
http.post(url, body: {'name': 'doodle', 'color': 'blue'}).then((response) {
   print('Response status: ${response?.statusCode}');
   print('Response body: ${response?.body}');
});
  • Related