toCamelCase method

String toCamelCase({
  1. bool addSpace = false,
})

The optional parameter addSpace determines whether to include spaces between the words in the resulting String. By default, it is set to false. If set to true, the resulting String will have spaces between the words.

The conversion is done by splitting the original String by any whitespace or underscore characters and then converting the first letter of each resulting word to lowercase (except for the first word, which is converted to all lowercase) while converting the rest of the letters to lowercase.

Example:

final String input = 'foo bar_baz';
final String output = input.toCamelCase(addSpace: true);
print(output); // Output: 'foo barBaz'

Implementation

String toCamelCase({bool addSpace = false}) {
  List<String> words = this.split(new RegExp(r'[\s_]+'));
  List<String> camelWords = [];
  for (int i = 0; i < words.length; i++) {
    String camelWord;
    if (i == 0) {
      camelWord = words[i].toLowerCase();
    } else {
      camelWord = '${words[i][0].toUpperCase()}${words[i].substring(1).toLowerCase()}';
    }
    camelWords.add(camelWord);
  }
  String result = camelWords.join(addSpace ? ' ' : '');
  return result;
}