How to Capitalize First Letter of Word and Sentence in Flutter

In this post, we are going to show you how to capitalize to uppercase the first letter of the string, or the first letter of each word, the first letter of a sentence in Flutter and Dart. These code examples ignore the white space and capitalize accordingly. 

String capitalize(String value) {
  var result = value[0].toUpperCase();
  bool cap = true;
  for (int i = 1; i < value.length; i++) {
      if (value[i - 1] == " " && cap == true) {
        result = result + value[i].toUpperCase();
      } else {
            result = result + value[i];
            cap = false;
      }
  }
  return result;
}
String str1 = capitalize("hello there. this is fluttercampus.");
print(str1); //Hello there. this is fluttercampus.

This function ignores the space. You can copy this function and use it on your Flutter project.

String capitalizeAllWord(String value) {
  var result = value[0].toUpperCase();
  for (int i = 1; i < value.length; i++) {
    if (value[i - 1] == " ") {
      result = result + value[i].toUpperCase();
    } else {
      result = result + value[i];
    }
  }
  return result;
}
String str2 = capitalizeAllWord("hello there. this is fluttercampus.");
print(str2); //Hello There. This Is Fluttercampus.

This function changes the first letter of each word of string to a capital letter in Flutter. This function also ignores the white space.

String capitalizeAllSentence(String value) {
  var result = value[0].toUpperCase();
  bool caps = false;
  bool start = true;

  for (int i = 1; i < value.length; i++) {
    if(start == true){
        if (value[i - 1] == " " && value[i] != " "){
            result = result + value[i].toUpperCase();
            start = false;
        }else{
            result = result + value[i];
        }
    }else{
      if (value[i - 1] == " " && caps == true) {
        result = result + value[i].toUpperCase();
        caps = false;
      } else {
          if(caps && value[i] != " "){
              result = result + value[i].toUpperCase();
              caps = false;
          }else{
              result = result + value[i];
          }
      }

      if(value[i] == "."){
          caps = true;
      }
    }  
  }
  return result;
}
String str3 = capitalizeAllSentence("hello there. this is fluttercampus.");
print(str3); //Hello There. This is fluttercampus.

This function converts the first letter of each sentence in the string to a capital letter. It uses the "." full stop as a reference to the sentence, and also ignores the single or multiple spaces in the string. 

In this way, you can capitalize the first letter of string, first letter of each word and first letter of each sentence in String. 

No any Comments on this Article


Please Wait...