utf16_safe_text 1.0.0 copy "utf16_safe_text: ^1.0.0" to clipboard
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 "
}
0
likes
160
points
5
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Truncate and sanitize Dart strings without splitting UTF-16 surrogate pairs. Prevents the not-well-formed-UTF-16 crash in Flutter text rendering.

Repository (GitHub)
View/report issues

Topics

#unicode #utf16 #string #emoji #text

License

MIT (license)

More

Packages that depend on utf16_safe_text