capitalize method

String capitalize({
  1. bool allWords = false,
})

Returns string with capitalized first letter.

Set allWords to true to capitalize every word separated by whitespace.

Example:

'test'.capitalize(); // 'Test'
'hello world'.capitalize(allWords: true); // 'Hello World'

Implementation

String capitalize({bool allWords = false}) {
  if (this == null || this!.isEmpty) return "";

  if (!allWords) {
    return '${this![0].toUpperCase()}${this!.substring(1)}';
  }

  if (this.isBlank) return '';

  return trimmed
      .split(RegExp(r'\s+'))
      .map((word) =>
          '${word[0].toUpperCase()}${word.substring(1).toLowerCase()}')
      .join(' ');
}