Dart/Flutter – How to capitalize first letter of each word in a String

In this post, I will show you an example of how to capitalize first letter of each word in a String. (This kind of String (capitalized first letter of each word) is called “title case”.)

As usual, I will jump directly to the code because there is no specific thing to explain.

void main() {
  String test = 'this is coflutter';

  // Output: This Is Coflutter
  print(convertToTitleCase(test)); 
}

String convertToTitleCase(String text) {
  if (text == null) {
    return null;
  }

  if (text.length <= 1) {
    return text.toUpperCase();
  }

  // Split string into multiple words
  final List<String> words = text.split(' ');

  // Capitalize first letter of each words
  final capitalizedWords = words.map((word) {
    if (word.trim().isNotEmpty) {
      final String firstLetter = word.trim().substring(0, 1).toUpperCase();
      final String remainingLetters = word.trim().substring(1);

      return '$firstLetter$remainingLetters';
    }
    return '';
  });

  // Join/Merge all words back to one String
  return capitalizedWords.join(' ');
}

Of course we can use Extension methods technique to wrap above method and have more beautiful code.

void main() {
  String test = 'this is coflutter';

  // Test extension, looks more beautiful, right?
  // same output: This Is Coflutter
  print(test.toTitleCase());
}

String convertToTitleCase(String text) {
  if (text == null) {
    return null;
  }

  if (text.length <= 1) {
    return text.toUpperCase();
  }

  // Split string into multiple words
  final List<String> words = text.split(' ');

  // Capitalize first letter of each words
  final capitalizedWords = words.map((word) {
    if (word.trim().isNotEmpty) {
      final String firstLetter = word.trim().substring(0, 1).toUpperCase();
      final String remainingLetters = word.trim().substring(1);

      return '$firstLetter$remainingLetters';
    }
    return '';
  });

  // Join/Merge all words back to one String
  return capitalizedWords.join(' ');
}

extension CapitalizedStringExtension on String {
  String toTitleCase() {
    return convertToTitleCase(this);
  }
}

If you are looking for mobile/web Software Engineers to build you next projects, please Contact Nextfunc team here!

Tagged : / / / /
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Bhanuka Isuru
Bhanuka Isuru
2 months ago

Got an error. try this String test = ‘this is(more than 1 space to here)coflutter’;;

Last edited 2 months ago by Bhanuka Isuru
2
0
Would love your thoughts, please comment.x
()
x