substringSafe method

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

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