Skip to content

Instantly share code, notes, and snippets.

@gboliknow
Created June 25, 2023 22:17
Show Gist options
  • Save gboliknow/0e47fdf8a8997d3a35bfd1c6af47792f to your computer and use it in GitHub Desktop.
Save gboliknow/0e47fdf8a8997d3a35bfd1c6af47792f to your computer and use it in GitHub Desktop.
How to solve issue with surrogate string in flutter and UTF-16
String get _getSubstringWithSurrogatePairs {
final substring = _text.substring(0, _maxTextLength);
final List<int> utf16Bytes = [...substring.codeUnits];
final int lastIndex = utf16Bytes.length - 1;
if (substring.length >= _maxTextLength) {
final int lastByte = utf16Bytes[lastIndex];
if (lastByte >= 56320 && lastByte <= 57343) {
// Last byte is a lower surrogate
return _text.substring(0, _maxTextLength);
} else if (lastByte >= 55296 && lastByte <= 56319) {
// Last byte is an upper surrogate
utf16Bytes.removeLast();
return String.fromCharCodes(utf16Bytes);
}
}
// Last byte is not part of an extended character with surrogate pairs
return _text.substring(0, _maxTextLength);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment