substringSafe method
Safely gets a substring, preventing RangeError (returns empty string for out-of-bounds indices). Prefer this over String.substring when indices may be invalid (e.g. user input or variable length).
Uses grapheme clusters for proper Unicode support. start is the
inclusive start index. end is the optional exclusive end index.
Example:
'๐hello'.substringSafe(0, 1); // '๐'
'hello'.substringSafe(1, 3); // 'el'
Implementation
@useResult
String substringSafe(int start, [int? end]) {
final Characters chars = characters;
final int charLength = chars.length;
if (start < 0 || start > charLength) {
return '';
}
if (end != null && end < start) {
return '';
}
final int clampedEnd = (end ?? charLength).clamp(start, charLength);
return chars.getRange(start, clampedEnd).string;
}