Search code examples
dartcapitalize

Creating a capitalize Method in Dart


I am trying to create a method in dart but have run into a wall. I was looking at how .toUpperCase(); and .toLowerCase(); were done. The method that I am trying to create is .capitalize();

I would like to call this method like this String hello = "WORLD".capitalize(); //World

Here is the code I have so far

String capitalize() {
return this.codeUnitAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

When running String hello = "WORLD".capitalize(); I get the following error

[38;5;124m[2015-6-4 11:37:13.011] Class 'String' has no instance method 'capitalize'.

NoSuchMethodError: method not found: 'capitalize'
Receiver: "WORLD"
Arguments: [][0m

I know i can call a function like String capitalize(String s) => s[0].toUpperCase() + s.substring(1); But would much rather keep string Manipulation calls the same.

Thanks and I appreciate any help:)


Solution

  • You cannot extend the String class like you want. Just use it like this:

    capitalize("WORLD");