substringSafe method
Safely gets a substring, preventing RangeError.
Uses grapheme clusters (user-perceived characters) for proper Unicode support, including emojis and other multi-code-unit characters.
Returns an empty string if start is out of bounds or parameters are invalid.
Note: Indices refer to grapheme clusters, not code units. For example, 'π¨βπ©βπ§βπ¦' (family emoji) counts as 1 grapheme, not 7 code units.
Example:
'πhello'.substringSafe(0, 1); // 'π' (not broken emoji)
'π¨βπ©βπ§βπ¦abc'.substringSafe(1); // 'abc'
'hello'.substringSafe(1, 3); // 'el'
Implementation
String substringSafe(int start, [int? end]) {
final Characters chars = characters;
final int charLength = chars.length;
// Validate the start index.
if (start < 0 || start > charLength) return '';
// If an end index is provided, validate it.
if (end != null) {
// Ensure end is not before start.
if (end < start) return '';
// Clamp the end index to the character length.
end = end > charLength ? charLength : end;
}
// Return the substring using grapheme-aware getRange.
return chars.getRange(start, end ?? charLength).string;
}