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
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 12. Challenge: Work with Lists Next episode: 14. Create a Conditional List

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 13. Understand Null Safety

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.

Null means nothing. Instead of putting in a strange grade, you simply put null which means that the quiz wasn’t taken. Now so far in this course, we haven’t run into null and that’s because by default, all variables contain a value. So in the case of a variable containing a null value, we have to let Dart know about it. We do this with the question mark. We simply write the type with a question mark after it.

So here I am defining strings for my first name and last name. But here is a string for the suffix.

Now here’s the thing with the suffix variable, it may or may not, contain value. It will either contain a String or it will be null. This means, you can’t just use it like you did with other variables. If you perform an operation on a null value, the program will crash. This means, you have to take account for null values.

One way we can do this is with an if-statement. We simply check to see if the suffix is null. If it isn’t null, we can actually access the value like we’d normally do.

Other times, we can access a null value, and if we encounter a null value, we can put a default value. For this, we use the if-null operator. The if-null operator returns the unwrapped value otherwise, we can put a default value.

In this case, we return a suffix but if there was no suffix, we simply return an empty string. Lets play around with null values when working with a list.

To get started, open up Dartpad. We’re going to create a list of grades like we did in a previous challenge, except this time, we’ll create a new list that contains null values. We’re going to use a constructor. A constructor is special way to create objects. In this case, we’ll use the empty constructor, indicating that the list is growable.

var grades = List<int?>.empty(growable: true);

You’ll learn about constructors in the next course. We’ve now defined a list that contains nullable values. Now lets add some grades.

grades.add(100);
grades.add(null);
grades.add(84);

In this case, the student scored a hundred for their first test, missed their second test and scored an eighty four on the final test. Now let’s add all the values together. First we’ll create a new total variable.

var total = 0;

Now let’s get the first value. We’ll store in a variable.

var firstTest = grades[0];

This stores the possible null result in a variable. We can’t access the variable without unwrapping it. For example, if we add it to the total variable, we get an error.

total += firstTest;

We have to unwrap the value. We do this in an if statement. Let’s delete the error. Now, let’s unwrap the value and add it to the value variable.

if (firstTest != null) {
    total += firstTest;
} 

Now let’s get the second test. It’s a null result which means, we’ll default it to a zero. Let’s add it.

total += grades[1] ?? 0;

In this case, we add a zero to the total and we don’t have to create another variable to unwrap. Now there is one other way to unwrap the value.

There is another way to unwrap the value, but this is a very dangerous method. Like playing with electric cables. In this case, we put an exclamation mark known as the assertion operator after a null variable, and it automatically unwraps the value for us. Awesome right? But what happens if the variable contains a null value and you try to unwrap the program? Well it will crash your program.

This means, you should only use this when you are absolutely sure that the variable contains a value. This means, in practical terms you will only be using this operator in a very small amount of situations.

Okay, let’s access the value for the last test. We’re going to unwrap it using the exclamation mark.

total += grades[2]!; 

This returns the current value. But keep in mind, this is a dangerous operation. If the variable actually contains a null value, then you will crash your program. You should only use it when know you that the variable contains a value. cWell this will crash your program.

Now, we can get the average.

var average = total / grades.length;
print('The average is $average');

Now, for giggles, let’s set our last test to null. When we run our program, we run into an error. In short, always be careful when using the exclamation mark.

Believe it or not, there are more ways to unwrap a null value. Dart provides a whole ton of them which you can check out in the author notes. Instead of barraging you with all the options, I’ll share new ones as we come into the them. Just note, if you are coming from a language like Swift and are curious for equivalents for unwrapping nulls, Dart has them in spades. For instance, if you check for a null value in a function and return out of it, that’s the Dart equivalent of the guard statement. Again, see the official documentation for more information.