http.post throws Bad state when I send a Map with a JSON Content-Type
Bad state: Cannot set the body fields of a Request with content-type "application/json".Short answer
In package:http a Map body means form fields, so the content type is fixed to application/x-www-form-urlencoded. Combining a Map with a Content-Type of application/json is refused with a StateError. To send JSON, turn the Map into a String with jsonEncode and set the header yourself. To send a form, drop the JSON header.
Fix it fast
1Find out which cause you have
Look at the call that sends the request. You are in this error when the body argument is a Map and the headers carry a JSON content type.
grep -rn -B2 -A8 "http.post\|http.Request(" lib/2Match what you see, then jump to its fix
- 1
body: {...} next to headers: {'Content-Type': 'application/json'}A Map is passed as the body of http.post while the header says JSONFix - 2
request.bodyFields = {...} together with request.headers['Content-Type'] = 'application/json'bodyFields is set on a Request that also carries a JSON Content-TypeFix - 3
The server documentation shows application/x-www-form-urlencoded or HTML form fieldsThe API wants form data, but the code sends a JSON headerFix
- 1
What does the error look like?
Bad state: Cannot set the body fields of a Request with content-type "application/json".StateError
Cause 1 of 3
A Map is passed as the body of http.post while the header says JSON
1Check
The post documentation lists three body types: a String, a List<int> or a Map<String, String>. A Map is encoded as form fields, and the content type is then set to application/x-www-form-urlencoded and cannot be overridden. A String body gets text/plain by default, so for JSON you set the header yourself.
grep -rn "Content-Type" lib/2Fix
Encode the Map to a JSON string with jsonEncode and send that String. Keep the JSON header.
import 'dart:convert';
import 'package:http/http.dart' as http;
final response = await http.post(
Uri.https('example.com', '/api/users'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'name': 'Aisha', 'age': 31}),
);3Verify
The request is sent and you get a status code and a body back, instead of a StateError.
print(response.statusCode);
print(response.body);Confirmed by pub.dev
Cause 2 of 3
bodyFields is set on a Request that also carries a JSON Content-Type
1Check
The bodyFields property is for form-encoded fields. The docs say that setting it on a request whose Content-Type header is anything other than application/x-www-form-urlencoded throws a StateError. Reading it in that state throws one too.
grep -rn "bodyFields" lib/2Fix
Set the body property instead, with a JSON string, and keep the JSON header. Use bodyFields only for real form data.
final request = http.Request('POST', Uri.https('example.com', '/api/users'))
..headers['Content-Type'] = 'application/json'
..body = jsonEncode({'name': 'Aisha', 'age': 31});
final streamed = await http.Client().send(request);3Verify
The call completes and streamed.statusCode is what the API returns.
print(streamed.statusCode);Confirmed by pub.dev
Cause 3 of 3
The API wants form data, but the code sends a JSON header
1Check
A Map<String, String> body is exactly what a form post needs, and the package sets the right content type for it. In that case the JSON header is the mistake, not the Map.
grep -rn "headers:" lib/2Fix
Remove the JSON Content-Type header and keep the Map of strings.
final response = await http.post(
Uri.https('example.com', '/login'),
body: {'email': 'aisha@example.com', 'password': 'secret'},
);3Verify
The server accepts the form and answers with a normal status code.
print(response.statusCode);Confirmed by pub.dev
How do I stop it coming back?
- Decide the format first: JSON means jsonEncode and a JSON header, a form means a Map of strings and no content type.
- Put API calls behind one small function per endpoint, so the body and the header are written together.
- Read the package documentation for the body type before you reach for a Map.
- Check that every value you pass to jsonEncode is a number, bool, string, null, list or map, or give it a toJson method.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Qist BazaarA buy-now-pay-later marketplace built from a blank repo, now past 100K downloads on Google Play.
- SessionBirdAn omnichannel engagement suite in Flutter: campaigns, chatbot, tickets, analytics and live calling.
Related fixes
Mobile apps
jsonEncode fails with 'Converting object to an encodable object failed'
Converting object did not return an encodable object: Instance of 'Address'
jsonEncode only handles numbers, booleans, strings, null, lists and maps with string keys.
3 causes, each with a fixMobile apps
Flutter jsonDecode fails with FormatException on an HTTP response
Instance of 'Response'
jsonDecode only parses JSON text.
2 causes, each with a fixMobile apps
AudioCache has no play method after updating audioplayers
The method 'play' isn't defined for the type 'AudioCache'.
Since audioplayers 1.0, AudioCache only turns asset files into local files and caches them.
2 causes, each with a fixMobile apps
Flutter Bloc throws that emit was called after the event handler completed
emit was called after an event handler completed normally.
Each on<Event> handler gets its own Emitter, and it stops working the moment the handler's returned Future completes.
2 causes, each with a fixMobile apps
analysis_options.yaml: the URI it includes can't be found
include_file_not_found
The analyzer reports include_file_not_found when the file named after include: in analysis_options.yaml does not resolve.
2 causes, each with a fixMobile apps
Dart error: the body might complete normally and return null for a non-nullable type
body_might_complete_normally
Dart found a path through your function or callback that reaches the closing brace without a return.
3 causes, each with a fix