safeSubstring static method

String safeSubstring(
  1. String s,
  2. int start, [
  3. int? end
])

Safely extracts a substring, adjusting indices to avoid cutting through UTF-16 surrogate pairs (e.g., emoji). If end is not provided, extracts from start to the end of the string.

Implementation

static String safeSubstring(String s, int start, [int? end]) {
  if (s.isEmpty) return s;
  final adjustedStart = adjustIndex(s, start.clamp(0, s.length));
  final adjustedEnd = end != null ? adjustIndex(s, end.clamp(0, s.length)) : s.length;
  if (adjustedStart >= adjustedEnd) return '';
  return s.substring(adjustedStart, adjustedEnd);
}