utf16_safe_text 1.0.0
utf16_safe_text: ^1.0.0 copied to clipboard
Truncate and sanitize Dart strings without splitting UTF-16 surrogate pairs. Prevents the not-well-formed-UTF-16 crash in Flutter text rendering.
example/utf16_safe_text_example.dart
import 'package:utf16_safe_text/utf16_safe_text.dart';
void main() {
const displayName = 'Cem π'; // 6 code units: the emoji occupies two
// A raw substring can cut the emoji in half. The result looks fine in a
// print statement but crashes Flutter's text renderer.
final unsafe = displayName.substring(0, 5);
print('raw substring well-formed? ${isWellFormedUtf16(unsafe)}'); // false
// safeTruncate drops the emoji whole instead.
final safe = safeTruncate(displayName, 5);
print('safeTruncate -> "$safe" (${isWellFormedUtf16(safe)})'); // "Cem " true
// Same thing as an extension.
print('extension -> "${displayName.truncateUtf16Safe(5)}"');
// For strings you did not truncate yourself β data from a database or another
// client that may already be malformed β repair before rendering.
final fromDatabase = 'Cem \uD83D'; // half an emoji, no partner
print('malformed? -> ${!fromDatabase.isWellFormedUtf16}'); // true
print('repaired -> "${fromDatabase.withoutLoneSurrogates}"'); // "Cem "
}