mostFrequent method Null safety

String? mostFrequent()

Finds the most frequent character in the String.

Example 1

String foo = 'Hello World';
String mostFrequent = foo.mostFrequent() // returns 'l'

Implementation

String? mostFrequent() {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return this;
  }
  var occurences = [];
  var letters = this!.split('')..sort();
  var checkingLetter = letters[0];
  var count = 0;
  for (var i = 0; i < letters.length; i++) {
    if (letters[i] == checkingLetter) {
      count++;
      if (i == letters.length - 1) {
        occurences.add({checkingLetter: count});
        checkingLetter = letters[i];
      }
    } else {
      occurences.add({checkingLetter: count});
      checkingLetter = letters[i];
      count = 1;
    }
  }
  var mostFrequent = '';
  var occursCount = -1;
  occurences.forEach((element) {
    element.forEach((character, occurs) {
      if (occurs > occursCount) {
        mostFrequent = character;
        occursCount = occurs;
      }
    });
  });
  return mostFrequent;
}