[SOLVED]: Cannot set the body fields of a Request with content-type “application/json”.

Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type “application/json”

While working with Flutter app and REST API, sometimes you might get an error: Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type “application/json”. This is most time happening when you are doing a post request with a content-type header: application/json.

For example:

await http.post(
  Uri.parse('https://oflutter.com/register'),
  body: {
    "email": email,
    "password": password,
    "token": token,
  },
  headers: {
    HttpHeaders.contentTypeHeader: 'application/json',
  },
);

The problem with this code is that we are setting a post request as an application/json format, however, in this body line of code, we are just passing as a map. We have to first convert our body fields to json format.

Solution: Use jsonEncode

To solve this error, we simply use the jsonEncode function to wrap our body fields.

  • Step #1: Import ‘dart:converter
  • Step #2: Wrap body with jsonEncode
import 'dart:convert';
await http.post(
  Uri.parse('https://oflutter.com/register'),
  body: jsonEncode({
    "email": email,
    "password": password,
    "token": token,
  }),
  headers: {
    HttpHeaders.contentTypeHeader: 'application/json',
  },
);

You May Also Like

Leave a Reply

Your email address will not be published.

eleven − ten =