flutter
data_error
ai_generated
true
FormatException: Unexpected character (at character 2)
ID: flutter/dart-format-exception-json-decode
90%Fix Rate
85%Confidence
1Evidence
2023-11-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Flutter 3.22.0 | active | — | — | — |
| Dart 3.4.0 | active | — | — | — |
| http 1.2.1 | active | — | — | — |
| dio 5.4.0 | active | — | — | — |
Root Cause
Invalid JSON string received from a network request or local file, possibly truncated or malformed.
generic中文
从网络请求或本地文件接收到的 JSON 字符串无效,可能被截断或格式错误。
Official Documentation
https://api.dart.dev/stable/3.4.0/dart-convert/FormatException-class.htmlWorkarounds
-
95% success Log the raw response body before decoding to inspect the actual content: `print(response.body);` and check for truncation or extra characters.
Log the raw response body before decoding to inspect the actual content: `print(response.body);` and check for truncation or extra characters.
-
80% success Use a JSON preprocessor to remove BOM or control characters: `String cleaned = response.body.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), '');` then decode.
Use a JSON preprocessor to remove BOM or control characters: `String cleaned = response.body.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), '');` then decode.
-
70% success Add a retry mechanism with exponential backoff for network requests to handle transient truncation.
Add a retry mechanism with exponential backoff for network requests to handle transient truncation.
中文步骤
Log the raw response body before decoding to inspect the actual content: `print(response.body);` and check for truncation or extra characters.
Use a JSON preprocessor to remove BOM or control characters: `String cleaned = response.body.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), '');` then decode.
Add a retry mechanism with exponential backoff for network requests to handle transient truncation.
Dead Ends
Common approaches that don't work:
-
90% fail
Ignoring the error leaves the app in an inconsistent state with null data, causing downstream crashes.
-
95% fail
The format exception is raised by Dart's standard decoder; other libraries use the same parser.
-
85% fail
The error is about JSON syntax, not character encoding; changing encoding may worsen the issue.