A Dart string “capitalize” function

I was surprised to learn that Dart doesn’t have a string capitalize method, so if you ever need a capitalize method/function, here’s a start towards a solution:

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);

That function will work with Dart strings like these:

print(capitalize('f'));
print(capitalize('fo'));
print(capitalize('foo'));

But it will fail if (a) the string is null, and (b) you’ll get an “Uncaught exception: RangeError (index): Index out of range: no indices are valid: 0” error/exception if the string is blank, like this:

print(capitalize(''));  // Uncaught exception: RangeError (index): Index out of range

I’m short on time today, so I’ll leave that solution as an exercise for the reader, but a simple solution is to check to see if the given string parameter is null or its length is less than one.

Here’s another example of how you can use this capitalize function:

final fruits = ['apple', 'banana', 'cherry'];
List<String> capFruits = fruits.map((fruit) => capitalize(fruit)).toList();
capFruits.forEach((f) => print(f));