帖子请求中的null调用了getter'length'

时间:2020-08-31 12:59:21

标签: flutter dart

我正在尝试向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');
  }
}

2 个答案:

答案 0 :(得分:1)

您的标题应该是

headers: {'Content-type': 'application/json','Accept': 'application/json'}

答案 1 :(得分:1)

尝试

var header = {
    "Content-Type": "application/json",
    "token": "my token ---- edited",
};

var body = jsonEncode({
    "car_id": "1",
  });