substringSafe method

String substringSafe(
  1. int start, [
  2. int? end
])

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;
}