Need Help with Null Safety (Chapter 8 - Challenge 2)

Programming novice here. Not gonna lie, that Nullability chapter went right over my head and I’m struggling with this compile-time message here. I’m using Dart version 2.12.
Ch 8 - Challenge 2

I found a solution that fixes the bug and makes the code shorter and (hopefully) easier to understand:

Map<String, int> characterFrequencyMap(String text) {
  final characterFrequencyMap = <String, int>{};
  for (var codePoint in text.runes) {
    final character = String.fromCharCode(codePoint);
    final frequency = characterFrequencyMap[character] ?? 0;
    characterFrequencyMap[character] = frequency + 1;
  }
  return characterFrequencyMap;
}

Here is what’s happening with the null safety here:

  • When searching the map for a string character, it’s possible that the character won’t be there. In that case you’ll get a null. However, instead of null you can use the ?? to tell Dart to use a different default value, in this case 0. Because of this, frequency is guaranteed to never be null.
  • If the character didn’t exist before, it will now be set with a frequency of 1. If it did previously exist then the frequency will be incremented by one.

Now that null safety is officially in the stable channel, chapter 7 needs a rewrite. Do you have any suggestions for what would make it more clear? Or can you say which part was the most confusing? That will help with the second edition.

1 Like

Thanks for the quick reply.

I like that snippet, it reads very well for me. As for as any suggestions for updates on the null safety, I have nothing in mind at this very second. However, I intend to read the book a few more times, and I’ll be sure to reach out if/when I find a concept difficult to understand. Again, thanks for the help!

1 Like