Search code examples
stringflutterdartletter

How to Capitalized each first letter for a Sentence in Flutter...?


I want to capitalize each first letter from a sentence for Flutter..??

This is a capitalized sentence I'm expecting from This Is A Capitalized Sentence


Solution

  • extension StringExtension on String {
      String capitalizeByWord() {
        if (trim().isEmpty) {
          return '';
        }
        return split(' ')
            .map((element) =>
                "${element[0].toUpperCase()}${element.substring(1).toLowerCase()}")
            .join(" ");
      }
    }
    

    Use extension like this. So that you can use capitalizeByWord on any String to convert it.

    void main() async {
      var data = 'this is a capitalized sentence';
      print(data.capitalizeByWord()); // This prints the result 'This Is A Capitalized Sentence'
    }