Flutter jsonDecode fails with FormatException on an HTTP response
Unhandled Exception: FormatException: Unexpected character (at character 1)Short answer
jsonDecode only parses JSON text. The exception means the string you gave it is not JSON. Either you passed the Response object instead of response.body, or the server sent something else, such as an HTML error page. Print the status code and the start of the body, then fix whichever one is wrong.
Fix it fast
1Find out which cause you have
Print what jsonDecode actually receives. The first characters of the body show whether it is JSON, HTML, or not a body at all.
final response = await http.get(Uri.parse('https://api.example.com/items')); print(response.statusCode); print(response.headers['content-type']); print(response.body.substring(0, response.body.length.clamp(0, 200)));2Match what you see, then jump to its fix
What does the error look like?
Unhandled Exception: FormatException: Unexpected character (at character 1)Instance of 'Response'FormatException: Unexpected character (at character 1) <!DOCTYPE html>
Cause 1 of 2
The Response object is decoded instead of its body
1Check
Search for the jsonDecode call and look at its argument. A Response is an object, not text. If the argument is the response variable itself, or a string built from it, the parser sees the object's default description and stops at character 1.
grep -rn "jsonDecode(" lib/2Fix
Decode the body property, as the Flutter networking recipe does, and cast the result to the shape you expect.
import 'dart:convert';
final data = jsonDecode(response.body) as Map<String, dynamic>;3Verify
Run the request again. The exception disappears and data holds your map.
print(data.keys);Confirmed by docs.flutter.dev
Cause 2 of 2
The server did not return JSON
1Check
Compare the status code and the content-type header from the first step. An error page from the server, a login redirect or a wrong URL returns a body that is not JSON, and FormatException carries that text as its source.
try {
jsonDecode(response.body);
} on FormatException catch (e) {
print(e.message);
print(e.offset);
print(e.source);
}2Fix
Check the status code before parsing, as the Flutter recipe does, and ask for JSON with an Accept header. Then correct the URL or the request until the server answers with 200 and a JSON body.
final response = await http.get(
Uri.parse('https://api.example.com/items'),
headers: {'Accept': 'application/json'},
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
} else {
throw Exception('Request failed: ${response.statusCode}');
}3Verify
The failing call now either returns parsed data or throws a clear status-code exception instead of a FormatException.
print(response.statusCode);Confirmed by docs.flutter.dev
How do I stop it coming back?
- Always parse response.body, never the response variable.
- Check statusCode before decoding, and throw a clear error for anything that is not a success.
- Send an Accept: application/json header on JSON endpoints.
- Catch FormatException around decoding and log its source and offset while developing.
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
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 fixMobile apps
Dart throws ConcurrentModificationError while looping over a list
ConcurrentModificationError
Dart throws this when a collection changes size while something iterates it.
2 causes, each with a fixMobile apps
Dart cannot turn a compact timestamp like 20201101153000 into a DateTime
FormatException: Invalid date format
DateTime.parse accepts a subset of ISO 8601, and a time part must be introduced by T or a space.
2 causes, each with a fix