substringSafe method
Safely gets a substring, preventing RangeError.
Returns an empty string if start
is out of bounds or parameters are invalid.
Implementation
String substringSafe(int start, [int? end]) {
// Validate the start index.
if (start < 0 || start > length) 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 string length.
end = end > length ? length : end;
}
// Return the substring with validated indices.
return substring(start, end);
}