toTitleCase method

String toTitleCase([
  1. bool? forceCase
])

Converts the string to title case, where the first letter of each word is capitalized. Optionally, the rest of the letters in each word can be forced to lower case.

If the string is blank, it returns a blank string.

If the string is in upper case, the forceCase parameter defaults to true, otherwise it defaults to false.

  • forceCase: If true, forces the rest of the letters in each word to be lower case. If false, leaves the rest of the letters unchanged. Defaults to false if the string is not in upper case.

Returns the string converted to title case.

Implementation

String toTitleCase([bool? forceCase]) {
  if (isBlank) {
    return blankIfNull;
  }

  if (isUpperCase) {
    forceCase ??= true;
  } else {
    forceCase ??= false;
  }

  var words = splitWords(WordSplitMode.keepSplitters);
  var result = '';

  for (var word in words) {
    if (word.length > 1) {
      result += '${word[0].toUpperCase()}${forceCase ? word.substring(1).toLowerCase() : word.substring(1)}';
    } else {
      result += word[0].toUpperCase();
    }
  }

  return result.trim();
}