# FormatException：无效的 UTF-8 字节序列

- **ID:** `flutter/formatexception-invalid-utf8-byte-sequence`
- **领域:** flutter
- **类别:** encoding_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

从网络或文件接收的数据不是有效的 UTF-8 编码，导致 Dart 的 utf8 解码器失败。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Flutter 3.7 | active | — | — |
| Flutter 3.10 | active | — | — |
| Flutter 3.13 | active | — | — |

## 解决方案

1. ```
   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
}
   ```
2. ```
   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'); }
   ```
3. ```
   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** — The error will reappear whenever malformed data is encountered; no resilience. (90% 失败率)
- **Using utf8.decode(bytes, allowMalformed: true) without logging** — Silently replaces invalid sequences with replacement characters, potentially corrupting data silently. (30% 失败率)
- **Assuming the data source will always send correct UTF-8** — External data sources (especially user input or legacy systems) often send non-UTF-8 encodings like Latin-1. (70% 失败率)
