stringflutterdartlettercapitalize

How to capitalize the first letter of a string in dart?


How do I capitalize the first character of a string, while not changing the case of any of the other letters?

For example, "this is a string" should give "This is a string".


Solution

  • Since dart version 2.6, dart supports extensions:

    extension StringExtension on String {
        String capitalize() {
          return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
        }
    }
    

    So you can just call your extension like this:

    import "string_extension.dart";
    
    var someCapitalizedString = "someString".capitalize();