Why This Happens
In Dart, jsonDecode throws a FormatException when the input string is not valid JSON. This commonly occurs when an API returns HTML error pages, empty responses, or malformed JSON. Always validate the response status code before parsing.
The Problem
final response = await http.get(uri);
final data = jsonDecode(response.body); // May not be JSON!The Fix
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
} else {
throw Exception('Server error: ${response.statusCode}');
}Step-by-Step Fix
- 1
Identify the error
Look at the FormatException about unexpected characters. The input to jsonDecode is not valid JSON.
- 2
Find the cause
Check the HTTP response body — it may be an HTML error page, empty, or truncated. Verify the status code before parsing.
- 3
Apply the fix
Check response.statusCode before calling jsonDecode, and handle non-200 responses appropriately.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free