我正在尝试向API发出发布请求,但我不知道为什么会这样。
这是我的代码:
print('THIS IS PRINTING');
var response = await http.post(url, body: body, headers: header);
print('This not printing (throwing error before it prints)');
这是我得到的错误:I/flutter ( 2417): NoSuchMethodError: The getter 'length' was called on null. I/flutter ( 2417): Receiver: null I/flutter ( 2417): Tried calling: length
我可以使用PostMan发出请求,并给出相同的字段和值,然后在dart上收到此错误。我也可以提出其他获取请求,而没有任何问题。
完整代码:
void getFavorites() async {
var url = "https://www.my-url-edited.com/favorite";
var header = {
"Content-Type": "application/x-www-form-urlencoded",
"token": "my token ---- edited",
};
var body = {
"car_id": "1",
"boat_id": null,
"habitation_id": null,
"product_id": null,
};
try {
print('print before post request --- working');
// var response = await http.post(url, body: body, headers: header);
var response = await http.post(url, body: body, headers: header);
print('This not printing (throwing error before it prints)');
print(response.body);
// var data = json.decode(response.body);
} catch (e) {
print(e);
throw Exception('Not connected to network');
}
}
最佳答案
您的标题应该是
headers: {'Content-type': 'application/json','Accept': 'application/json'}
关于flutter - 帖子请求中的null调用了getter 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63671298/