5

I want to make a post request in Flutter with the following code:

// Body: {"email": "example@email.com", "pass": "passw0rd"}

Future<dynamic> post(String url, var body) async {
  var response = await http.post(url, body: body);
  final String res = response.body;
  return res;
}

// That's not the full code. I removed some lines because they are useless for this thread.
// Most of them are only some debug outputs or conditional statements

The problem is that my post request doesn't include the body with my request. I checked that with some outputs on my server.

Richard Heap
  • 48,344
  • 9
  • 130
  • 112
Keanu Hie
  • 297
  • 2
  • 8
  • 12
  • 1
    Try sending the request to `httpbin.org/post` which will echo the request. Perhaps you are missing a request header. Can you perform a valid post with curl or Postman? – Richard Heap Dec 15 '18 at 12:06

1 Answers1

11

You just have to encode the body before sending:

import 'dart:convert';
...

var bodyEncoded = json.encode(body);
var response = await http.post(url, body: bodyEncoded , headers: {
  "Content-Type": "application/json"
},);
SwiftiSwift
  • 7,528
  • 9
  • 56
  • 96
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • 2
    Thanks for the help. I also had to add "Content-Type": "application/x-www-form-urlencoded" to the headers to make it work. – Keanu Hie Dec 16 '18 at 07:46
  • 6
    For me it was `headers: {"Content-Type": "application/json"}` :) See also https://stackoverflow.com/questions/27574740/http-post-request-with-json-content-type-in-dartio – Hugo H Sep 06 '19 at 07:50