Unicode and encodings
suggest changeText handling bugs usually come from mixing up three different units:
- Code unit: one 16-bit value. A Dart
Stringis a sequence of UTF-16 code units, andlength, indexing (s[i]) andsubstring()all work on code units. - Code point (a rune in Dart): one Unicode character number, from
U+0000toU+10FFFF. Characters aboveU+FFFF, such as most emoji, take two code units (a surrogate pair). - Grapheme cluster: what a user sees as one character. It can be made of several code points, for example a letter plus an accent, a flag, or an emoji with a skin tone.
Bytes are a fourth unit. When text leaves your program (files, sockets, HTTP) it's encoded into bytes, almost always as UTF-8. The dart:convert library provides the utf8, latin1 and ascii codecs for that.
Code units, runes and bytes
This program shows how the same string has a different size depending on what you count:
import 'dart:convert';
String hex(int n) => 'U+${n.toRadixString(16).toUpperCase().padLeft(4, '0')}';
void main() {
const s = 'Aé€😀';
print('code units: ${s.length}'); // 5
print('runes: ${s.runes.length}'); // 4
print('UTF-8 bytes: ${utf8.encode(s).length}'); // 10
for (final rune in s.runes) {
final ch = String.fromCharCode(rune);
print('$ch ${hex(rune)} utf8=${utf8.encode(ch)}');
}
print(s.codeUnits); // [65, 233, 8364, 55357, 56832]
}
Output:
code units: 5
runes: 4
UTF-8 bytes: 10
A U+0041 utf8=[65]
é U+00E9 utf8=[195, 169]
€ U+20AC utf8=[226, 130, 172]
😀 U+1F600 utf8=[240, 159, 152, 128]
[65, 233, 8364, 55357, 56832]
😀 (U+1F600) doesn't fit in 16 bits, so it is stored as the surrogate pair 0xD83D 0xDE00 (55357, 56832). s.runes combines surrogate pairs back into code points; s.codeUnits doesn't.
In UTF-8 a code point takes 1 to 4 bytes: ASCII takes 1, most European letters 2, most other characters (including CJK) 3, and emoji 4.
Writing Unicode in source code
Dart source files are UTF-8, so you can type any character directly in a string literal. You can also use escapes, which is useful for invisible or confusable characters:
void main() {
print('\u00E9'); // é (exactly 4 hex digits)
print('\u{1F600}'); // 😀 (1 to 6 hex digits in braces)
print('\xE9'); // é (exactly 2 hex digits)
print('a\u00A0b'.length); // 3 (no-break space)
print(String.fromCharCode(0x1F600)); // 😀
print(String.fromCharCodes([72, 105, 0x1F44B])); // Hi👋
print('é'.codeUnitAt(0)); // 233
print('😀'.runes.first.toRadixString(16)); // 1f600
}
String.fromCharCode() accepts any code point and creates a surrogate pair when needed. In raw strings (r'é') escapes aren't processed.
Surrogate pairs and broken strings
Because length, [] and substring() count code units, they can cut a surrogate pair in half. The result is a string with a lone surrogate, which isn't valid Unicode. When it's encoded as UTF-8, the broken half becomes the replacement character U+FFFD (�):
import 'dart:convert';
void main() {
const s = 'ok😀';
print(s.length); // 4
print(s[2]); // a lone high surrogate, printed as �
final cut = s.substring(0, 3);
print(utf8.encode(cut)); // [111, 107, 239, 191, 189]
// Detect lone surrogates: well-formed pairs are combined by runes.
bool hasLoneSurrogate(String s) =>
s.runes.any((r) => r >= 0xD800 && r <= 0xDFFF);
print(hasLoneSurrogate(s)); // false
print(hasLoneSurrogate(cut)); // true
}
The bytes 239, 191, 189 are the UTF-8 encoding of U+FFFD. Data is silently lost, so avoid code unit indexes when slicing text that can contain emoji or other characters outside the Basic Multilingual Plane.
Common operations that work on code units:
s.length,s[i],s.substring(),s.codeUnitAt()s.split(''), which splits into code units, not characterss.padLeft()/s.padRight(), which count code units when paddings.compareTo(), which orders strings by code unit values
Grapheme clusters with package:characters
Runes are still not "characters" from a user's point of view. A flag is two code points, a family emoji is five code points joined by zero-width joiners (U+200D), and é can be written as e followed by a combining accent U+0301.
The characters package, maintained by the Dart team, splits a string into grapheme clusters according to the Unicode rules:
dart pub add characters
Flutter already re-exports it, so in a Flutter app 'text'.characters works without adding the dependency.
import 'dart:convert';
import 'package:characters/characters.dart';
void main() {
const s = 'Hi 👋🏽 🇵🇱 👨👩👧';
print('code units: ${s.length}');
print('runes: ${s.runes.length}');
print('characters: ${s.characters.length}');
print('UTF-8 bytes: ${utf8.encode(s).length}');
for (final ch in s.characters) {
print('"$ch" units=${ch.length} runes=${ch.runes.length}');
}
}
Output:
code units: 21
runes: 14
characters: 8
UTF-8 bytes: 39
"H" units=1 runes=1
"i" units=1 runes=1
" " units=1 runes=1
"👋🏽" units=4 runes=2
" " units=1 runes=1
"🇵🇱" units=4 runes=2
" " units=1 runes=1
"👨👩👧" units=8 runes=5
s.characters returns a Characters object, which is an Iterable<String> with extra methods. Use it whenever you truncate, reverse or count text that a person will see, for example to enforce a "max 20 characters" limit on a user name:
import 'package:characters/characters.dart';
void main() {
const s = 'Hi 👋🏽 there';
// Wrong: cuts the emoji in half.
print(s.substring(0, 4)); // Hi �
// Right: take whole grapheme clusters.
print(s.characters.take(4).toString()); // Hi 👋🏽
print(s.characters.first); // H
print(s.characters.skip(3).first); // 👋🏽
// Reversing.
const flag = 'abc🇵🇱';
print(String.fromCharCodes(flag.runes.toList().reversed)); // 🇱🇵cba (wrong flag)
print(flag.characters.toList().reversed.join()); // 🇵🇱cba
// Truncate with an ellipsis.
String ellipsize(String text, int max) {
final chars = text.characters;
if (chars.length <= max) return text;
return '${chars.take(max - 1)}…';
}
print(ellipsize('Zażółć gęślą jaźń 🎉🎉', 8)); // Zażółć …
}
Reversing runes swaps the two regional indicator letters, turning the Polish flag PL into LP. Only grapheme-aware code gets this right.
Encoding to and from UTF-8
utf8.encode() turns a String into a Uint8List and utf8.decode() does the reverse. utf8 is a Codec, and its utf8.encoder / utf8.decoder properties are converters you can use with streams:
import 'dart:convert';
void main() {
const text = 'Zażółć gęślą jaźń';
final bytes = utf8.encode(text);
print(bytes.length); // 26
print(text.length); // 17
final back = utf8.decode(bytes);
print(back == text); // true
// Invalid UTF-8 throws by default.
final bad = [0x48, 0x69, 0xFF, 0x21];
try {
utf8.decode(bad);
} on FormatException catch (e) {
print('FormatException: ${e.message}');
}
// Or replace invalid sequences with U+FFFD.
print(utf8.decode(bad, allowMalformed: true)); // Hi�!
}
Use the default (throwing) mode when invalid data should be rejected, for example when validating an upload. Use allowMalformed: true when you'd rather show slightly damaged text than fail, for example when displaying log files.
A common need is limiting the size of a string in bytes, for example for a database column or a protocol field. Cutting the byte list can split a multi-byte sequence, so cut at code point boundaries instead:
import 'dart:convert';
int utf8Length(int rune) => rune < 0x80
? 1
: rune < 0x800
? 2
: rune < 0x10000
? 3
: 4;
String truncateUtf8(String s, int maxBytes) {
var used = 0;
final out = StringBuffer();
for (final rune in s.runes) {
final n = utf8Length(rune);
if (used + n > maxBytes) break;
used += n;
out.writeCharCode(rune);
}
return out.toString();
}
void main() {
const s = 'Zażółć gęślą jaźń';
final t = truncateUtf8(s, 10);
print(t); // Zażółć
print(utf8.encode(t).length); // 10
// The naive version produces invalid UTF-8.
final naive = utf8.encode(s).sublist(0, 9);
print(utf8.decode(naive, allowMalformed: true)); // Zażół�
}
This keeps whole code points. If you also want to keep whole grapheme clusters, iterate over s.characters and use utf8.encode(ch).length for each one.
Decoding streams
When bytes arrive in chunks (files, sockets, HTTP responses), a multi-byte character can be split between two chunks. Decoding each chunk separately corrupts it. utf8.decoder used as a stream transformer keeps the incomplete sequence until the next chunk arrives:
import 'dart:convert';
Future<void> main() async {
final bytes = utf8.encode('żółw');
final chunks = [bytes.sublist(0, 1), bytes.sublist(1)];
// Wrong: decode chunks one by one.
print(chunks.map((c) => utf8.decode(c, allowMalformed: true)).join());
// ��ółw
// Right: decode the stream.
final text = await Stream<List<int>>.fromIterable(chunks).transform(utf8.decoder).join();
print(text); // żółw
}
The same pattern reads a large text file line by line without loading it into memory:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final lines = File('data.txt')
.openRead()
.transform(utf8.decoder)
.transform(const LineSplitter());
var count = 0;
await for (final line in lines) {
count++;
if (count <= 3) print(line);
}
print('$count lines');
}
For small files, File.readAsString() and File.writeAsString() use UTF-8 by default. Both take an encoding parameter for other encodings:
import 'dart:convert';
import 'dart:io';
Future<void> main() async {
final file = File('latin1.txt');
await file.writeAsString('café', encoding: latin1);
print(await file.length()); // 4 (é is a single byte in Latin-1)
print(await file.readAsString(encoding: latin1)); // café
try {
await file.readAsString(); // UTF-8 by default
} on FileSystemException catch (e) {
print('not valid UTF-8: ${e.message}');
}
}
Byte order mark
Some Windows tools write UTF-8 files that start with a byte order mark (BOM), the bytes EF BB BF. utf8.decode() keeps it as the invisible character U+FEFF at the start of the string, which can break parsing (the first CSV header or JSON key won't match). Strip it after decoding:
import 'dart:convert';
String decodeUtf8(List<int> bytes) {
final s = utf8.decode(bytes);
return s.startsWith('\uFEFF') ? s.substring(1) : s;
}
void main() {
final bytes = [0xEF, 0xBB, 0xBF, ...utf8.encode('id,name')];
final s = decodeUtf8(bytes);
print(s.length); // 7
print(s.split(',').first == 'id'); // true
}
Latin-1, ASCII and other encodings
dart:convert also provides latin1 (ISO-8859-1, code points U+0000 to U+00FF, one byte each) and ascii (7-bit). Encoding a character that doesn't fit throws an ArgumentError:
import 'dart:convert';
void main() {
print(latin1.encode('café')); // [99, 97, 102, 233]
print(latin1.decode([99, 97, 102, 233])); // café
try {
latin1.encode('5 €');
} on ArgumentError {
print('€ is not in Latin-1');
}
print(ascii.encode('plain')); // [112, 108, 97, 105, 110]
print(ascii.decode([104, 105, 200], allowInvalid: true)); // hi�
// Look up a codec by name, e.g. from a Content-Type charset.
print(Encoding.getByName('utf-8')?.name); // utf-8
print(Encoding.getByName('ISO-8859-1')?.name); // iso-8859-1
print(Encoding.getByName('us-ascii')?.name); // us-ascii
print(Encoding.getByName('shift_jis')); // null
}
Encoding.getByName() returns null for encodings the SDK doesn't support. For legacy encodings such as Windows-1252, Shift_JIS or GBK, use a package from pub.dev such as enough_convert or charset.
dart:io also has systemEncoding, the encoding of the operating system's console. It's the default for Process.run() output; pass stdoutEncoding: utf8 when you know the program prints UTF-8. See Running OS commands.
With the http package, response.body decodes the bytes using the charset from the Content-Type header and falls back to Latin-1 when it's missing. If you know the server sends UTF-8, decode the raw bytes yourself:
final text = utf8.decode(response.bodyBytes);
UTF-16
There's no UTF-16 codec in the SDK, but since Dart strings already are UTF-16 it's easy to convert to and from bytes, for example to read a UTF-16LE file written by Windows tools:
import 'dart:typed_data';
Uint8List encodeUtf16le(String s) {
final out = Uint8List(s.length * 2);
for (var i = 0; i < s.length; i++) {
final unit = s.codeUnitAt(i);
out[2 * i] = unit & 0xFF;
out[2 * i + 1] = unit >> 8;
}
return out;
}
String decodeUtf16le(Uint8List bytes) {
var start = 0;
if (bytes.length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE) {
start = 2; // skip BOM
}
final units = <int>[];
for (var i = start; i + 1 < bytes.length; i += 2) {
units.add(bytes[i] | (bytes[i + 1] << 8));
}
return String.fromCharCodes(units);
}
void main() {
final bytes = encodeUtf16le('Hi😀');
print(bytes); // [72, 0, 105, 0, 61, 216, 0, 222]
print(decodeUtf16le(bytes)); // Hi😀
}
String.fromCharCodes() combines the surrogate code units back into a single emoji.
Normalization
The same text can be represented by different sequences of code points. é can be the single code point U+00E9 (composed, NFC) or e followed by U+0301 COMBINING ACUTE ACCENT (decomposed, NFD). macOS file names and some keyboards produce the decomposed form. Dart compares strings code unit by code unit, so these look identical but are not equal:
import 'package:characters/characters.dart';
void main() {
const composed = 'café';
const decomposed = 'cafe\u0301';
print('$composed $decomposed'); // café café
print(composed == decomposed); // false
print('${composed.length} ${decomposed.length}'); // 4 5
print('${composed.characters.length} ${decomposed.characters.length}'); // 4 4
}
The SDK has no normalization function. Use the unorm_dart package to normalize before comparing, hashing or storing keys:
dart pub add unorm_dart
import 'package:unorm_dart/unorm_dart.dart' as unorm;
void main() {
const composed = 'café';
const decomposed = 'cafe\u0301';
print(unorm.nfc(decomposed) == composed); // true
print(unorm.nfd(composed).length); // 5
// Compatibility forms also fold ligatures, circled digits, etc.
print(unorm.nfkc('file ①')); // file 1
}
Use NFC for storing and comparing ordinary text. Use NFKC when matching identifiers or search terms where fi and fi should be considered the same.
Case conversion and comparison
toUpperCase() and toLowerCase() handle non-ASCII letters, and are not locale-specific:
void main() {
print('Zażółć'.toUpperCase()); // ZAŻÓŁĆ
print('ΑΘΗΝΑ'.toLowerCase()); // αθηνα
bool equalsIgnoreCase(String a, String b) =>
a.toLowerCase() == b.toLowerCase();
print(equalsIgnoreCase('Ärger', 'äRGER')); // true
final words = ['zebra', 'Äpfel', 'apple', 'Zoo'];
words.sort();
print(words); // [Zoo, apple, zebra, Äpfel]
}
sort() uses compareTo(), which compares code units: uppercase ASCII comes before lowercase, and accented letters come after z. For user-facing sorting, compare a normalized key such as a.toLowerCase().compareTo(b.toLowerCase()), or use locale-aware collation from a package. See Sorting and Localization.
Unicode in regular expressions
By default RegExp works on code units, so . matches half of a surrogate pair. Pass unicode: true to work on code points and enable Unicode property escapes such as \p{L} (any letter) and \p{N} (any number):
void main() {
print(RegExp(r'^.$').hasMatch('😀')); // false (2 code units)
print(RegExp(r'^.$', unicode: true).hasMatch('😀')); // true
final letters = RegExp(r'\p{L}+', unicode: true);
print(letters.allMatches('naïve 日本語 42!').map((m) => m[0]).toList());
// [naïve, 日本語]
// \w is ASCII only, even with unicode: true.
print(RegExp(r'\w+').allMatches('naïve').map((m) => m[0]).toList());
// [na, ve]
final upper = RegExp(r'\p{Lu}', unicode: true);
print('Ćma Żuk'.replaceAll(upper, '_')); // _ma _uk
}
See Regular Expressions for more about RegExp.
Tips
- Use
s.lengthonly for code unit math (indexes, buffers). For a user-visible character count, uses.characters.length. For a size in bytes, useutf8.encode(s).length. - Never slice user text with
substring()at arbitrary positions. Uses.characters.take(n)or cut at rune boundaries. - Always specify UTF-8 explicitly at boundaries where the default isn't UTF-8, such as
Process.run()output andhttpresponses without a charset. - Decode streams with
utf8.decoderas a transformer, never chunk by chunk. - Normalize to NFC before comparing or using strings as map keys if the text can come from different platforms.
base64.encode(s.codeUnits)is wrong for non-ASCII text. Encode to UTF-8 bytes first, as shown in Base64 and hex encoding.