我正在 dart 中開發一個應用程式。我使用http包。我從檔案中復制了示例代碼:
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}');
并得到這個錯誤:
Error: The await expression can only be used in an async function.
我不知道為什么這不起作用。它自己的例子。
uj5u.com熱心網友回復:
您需要確保您的代碼寫在 Future 函式中,如下所示:
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}');
}
或者,如果您不能這樣做,請使用.then()語法
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}');
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/398571.html
上一篇:在dartpub中更新已發布的包
