Programming in Dart: Fundamentals

Apr 26 2022 Dart 2.15, DartPad, DartPad

Part 2: Introducing Collections & Null Safety

13. Understand Null Safety

Episode complete

Play next episode

Next
Save for later
About this episode
See versions
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 12. Challenge: Work with Lists Next episode: 14. Create a Conditional List

This video Understand Null Safety was last updated on Apr 26 2022

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.

In 2021, Dart was upgraded with a huge feature that would affect every single line of Dart. And that was null safety. It was a huge upgrade and it really comes into play when working with collections. So what is null safety? What is being null? Null means the absence of a value. Lets say you are teacher, writing some code to make correcting grades easier for you. You may create a quiz but how do you know that a student has actually taken the quiz? Well, you could set the quiz value to zero, but that’s an actual grade. So you may next choose a negative number like negative one but what if your data store doesn’t accept negative numbers? After all, you can’t actually have a negative grade? You could solve this problem in a variety of ways but with null, it’s already solved for you.

var grades = List<int?>.empty(growable: true);
grades.add(100);
grades.add(null);
grades.add(84);
var total = 0;
var firstTest = grades[0];
total += firstTest;
if (firstTest != null) {
    total += firstTest;
} 
total += grades[1] ?? 0;
total += grades[2]!; 
var average = total / grades.length;
print('The average is $average');