# FormatException: Invalid UTF-8 byte sequence

- **ID:** `flutter/formatexception-invalid-utf8-byte-sequence`
- **Domain:** flutter
- **Category:** encoding_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

Data received from network or file is not valid UTF-8 encoded, causing Dart's utf8 decoder to fail.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Flutter 3.7 | active | — | — |
| Flutter 3.10 | active | — | — |
| Flutter 3.13 | active | — | — |

## Workarounds

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
}** (88% success)
   ```
   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'); }** (85% success)
   ```
   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.** (90% success)
   ```
   Before decoding, validate bytes with a BOM (Byte Order Mark) or use a library like 'chardet' to auto-detect encoding.
   ```

## Dead Ends

- **Ignoring the error and assuming data is always valid UTF-8** — The error will reappear whenever malformed data is encountered; no resilience. (90% fail)
- **Using utf8.decode(bytes, allowMalformed: true) without logging** — Silently replaces invalid sequences with replacement characters, potentially corrupting data silently. (30% fail)
- **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% fail)
