flutter
encoding_error
ai_generated
true
FormatException:无效的 UTF-8 字节序列
FormatException: Invalid UTF-8 byte sequence
ID: flutter/formatexception-invalid-utf8-byte-sequence
85%修复率
82%置信度
1证据数
2023-06-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Flutter 3.7 | active | — | — | — |
| Flutter 3.10 | active | — | — | — |
| Flutter 3.13 | active | — | — | — |
根因分析
从网络或文件接收的数据不是有效的 UTF-8 编码,导致 Dart 的 utf8 解码器失败。
English
Data received from network or file is not valid UTF-8 encoded, causing Dart's utf8 decoder to fail.
官方文档
https://api.dart.dev/stable/dart-convert/Utf8Decoder-class.html解决方案
-
Detect encoding first using package like 'charset' or 'universal_io' and decode with correct encoding: import 'dart:convert'; import 'package:charset/charset.dart'; List<int> bytes = ...; String text; try { text = utf8.decode(bytes); } on FormatException { text = latin1.decode(bytes); // fallback } -
Use utf8.decode(bytes, allowMalformed: true) and then sanitize or log replacement characters for debugging: String text = utf8.decode(bytes, allowMalformed: true); if (text.contains('\uFFFD')) { print('Malformed data detected'); } -
Before decoding, validate bytes with a BOM (Byte Order Mark) or use a library like 'chardet' to auto-detect encoding.
无效尝试
常见但无效的做法:
-
Ignoring the error and assuming data is always valid UTF-8
90% 失败
The error will reappear whenever malformed data is encountered; no resilience.
-
Using utf8.decode(bytes, allowMalformed: true) without logging
30% 失败
Silently replaces invalid sequences with replacement characters, potentially corrupting data silently.
-
Assuming the data source will always send correct UTF-8
70% 失败
External data sources (especially user input or legacy systems) often send non-UTF-8 encodings like Latin-1.