charOccurences method Null safety

List<Map<String, int>>? charOccurences()

Finds all character ooccurences and returns count as:

List<Map<dynamic,dynamic>>

Example 1

String foo = 'esentis';
List occurences = foo.charOccurences(); // returns '[{e:2},{i:1},{n:1},{s:2},]'

Implementation

List<Map<String, int>>? charOccurences() {
  if (this == null) {
    return null;
  }
  if (this!.isEmpty) {
    return [];
  }

  // ignore: omit_local_variable_types
  List<Map<String, int>> 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;
    }
  }
  return occurences;
}