flutter encoding_error ai_generated true

FormatException:无效的 UTF-8 字节序列

FormatException: Invalid UTF-8 byte sequence

ID: flutter/formatexception-invalid-utf8-byte-sequence

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://api.dart.dev/stable/dart-convert/Utf8Decoder-class.html

解决方案

  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.

无效尝试

常见但无效的做法:

  1. Ignoring the error and assuming data is always valid UTF-8 90% 失败

    The error will reappear whenever malformed data is encountered; no resilience.

  2. Using utf8.decode(bytes, allowMalformed: true) without logging 30% 失败

    Silently replaces invalid sequences with replacement characters, potentially corrupting data silently.

  3. 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.