Peter
Peter Software Developer | Technical Writer | Actively helping users with their questions on Stack Overflow. Occasionally I post here and on other platforms.

Using Null Safety In Dart

Using Null Safety In Dart
Source Code Follow me on

In this article, we will try the new feature in Dart which is null safety and we will see how it can help us to avoid annoying errors.

Get Started With Null Safety

You can check other Flutter articles that use null safety in the below links:

Starting with Dart 2.1.2 null safety is now stable, if you are working on Flutter you can then upgrade to the latest version by executing the command:

1
flutter upgrade

To make sure that the update working correctly, you can execute flutter --version, which should give you the following output:

1
2
3
4
Flutter 2.0.0 • channel stable • https://github.com/flutter/flutter
Framework • revision 60bd88df91 (14 hours ago) • 2021-03-03 09:13:17 -0800
Engine • revision 40441def69
Tools • Dart 2.12.0

What Is Null Safety

In simple terms, when we write any code in Dart and run it, the code will go through the DartVM. If we don’t initialize those variables then we will get an error. For example:

1
2
3
4
5
6
7
8
void main() {
  Students student;
  print(student.name);
}

class Students {
String name = "peter";
}

In the above Dart code, we create a class Students with one instance variable, then in the main() function we create a variable of type Students and call name on it. But the problem here, is that we didn’t create any student! Therefore the code above will return an error:

1
cannot read property name of null

Usually when we get this error, we then check if the object is initialized or not. In the above case it wasn’t initialized. Therefore to solve this we can do:

1
2
3
4
void main() {
  Students student = new Students();
  print(student.name);
}

In the above simple code it is easy to determine which variable is not initialized, but in a large codebase it becomes difficult and time consuming and that’s what null safety solves, which we will see in the following section.

Using Null Safety

Using the code in the previous section, even before running the application we would get the following error:

null dart flutter

This means that variable students cannot be null, with null safety enabled in Flutter/Dart you cannot have any variable that is equal to null unless you specify. That is very helpful since you can catch the problems even before running the code and now you do not have to keep checking if a variable is null or not before using a property or method on it. To solve the error we can then just initialize the student variable as I showed in the previous section.

Nullable Type

To specify if the variable can be null, then you can use the nullable type ? operator, for example:

1
2
3
4
5
6
7
void main() {
  Students? student;
}

class Students {
String name = "peter";
}

Using the operator ? in Dart, basically means that the student variable can be equal to null. Now if you want to call name on student, you will get the following error:

null dart flutter

So as the error says, you need to use the ?. operator since student can be null so you have to do the following:

1
2
3
4
5
6
7
8
void main() {
  Students? student;
  print(student?.name);
}

class Students {
String name = "peter";
}

This will print null in the console. Another way is to use the postfix operator !, using this operator an error will be thrown in the console, for example:

1
2
3
4
5
6
7
8
void main() {
  Students? student;
  print(student!.name);
}

class Students {
String name = "peter";
}

This will throw the following error in the console:

1
Uncaught TypeError: Cannot read property 'get$name' of nullError: TypeError: Cannot read property 'get$name' of null

Also the postfix operator ! will cast the variable to its underlying non-nullable type. For example:

1
2
class HomePage extends StatefulWidget {
  final String? message;

If you have the above under the HomePage declaration, then you need to use that message in a Text widget:

1
Text(widget.message!)

Here we have to use the postfix operator, because the Text() widget takes a value of type String as an argument, while the variable message is of type String? which means it can be null. Therefore by using the postfix operator, it will cast the variable message to String. You can check more here


required Keyword

Another new keyword added to Dart, is the required keyword. The required keyword can be used with optional named parameter, this way any variable that is required must be passed as a parameter when calling the function. Let’s see the counter application example:

1
2
3
class MyHomePage extends StatefulWidget {
   final String title;
  MyHomePage({Key? key, this.title}) : super(key: key);

Here as you can see the title variable is non null by default therefore the above code will give the following error:

null dart flutter

To solve this error, you can add the required keyword before the variable:

1
2
3
class MyHomePage extends StatefulWidget {
   final String title;
  MyHomePage({Key? key, required this.title}) : super(key: key);

late Keyword

Another new keyword added is the late keyword. Since all variables are non null by default then we can either use the ? operator or we can use the late keyword. For example:

1
2
3
4
class Students {
 String? name;
}

By using the non nullable type operator ?, it means that name can be null, to solve that we use late which basically means late initialization:

1
2
3
class Students {
 late String name;
}

I hope you enjoyed this article, for more detailed information check the dart documentation. If you are looking for mobile app developer jobs, you can check them here .

 

Become a Patron!