removeConsecutiveSpaces method

String? removeConsecutiveSpaces({
  1. bool trim = true,
})

Extension method to remove consecutive spaces in a String and optionally trim the result.

Implementation

String? removeConsecutiveSpaces({bool trim = true}) {
  // Handle empty string case.
  if (isEmpty) {
    return null;
  }
  // The regex \s+ matches one or more whitespace characters.
  final String replaced = replaceAll(RegExp(r'\s+'), ' ');
  // Return the result, potentially trimmed and checked for emptiness.
  return replaced.nullIfEmpty(trimFirst: trim);
}