Problem
When sending an HTTP request in Flutter, you may want to decode the JSON response. When doing so, you may encounter the following error:
Flutter FormatException: Unexpected character (at character 1)
This error is caused by the wrong JSON format you get from the response body (e.g. it doesn’t start with an open curly bracket “{“).
Solutions
Printing out the response.body, see the output, and try one of the following solutions:
1. Correct the API endpoint if there is something wrong with it.
2. Provide header information when sending a request:
{
'Content-Type': 'application/json',
'Charset': 'utf-8'
}
3. The API may need some auth credentials like username, password, token… Provide them if needed.
4. Maybe the bug isn’t in your Flutter code but on the server side. Review it or communicate with the backend developers in your team.
Hope you’ll get through the annoying problem soon. Further reading:
- How to encode/decode JSON in Flutter
- How to read data from local JSON files in Flutter
- Best Libraries for Making HTTP Requests in Flutter
- Flutter and Firestore Database: CRUD example
- Dart: Convert Class Instances (Objects) to Maps and Vice Versa
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.