DEV Community

Cover image for Null safety explained.
J Mohammed khalif
J Mohammed khalif

Posted on • Edited on

Null safety explained.

The Dart language has recently been on the rise due to the exploding popularity of its child framework- flutter. The language has a unique feature called null safety and I bet you must have heard about it if you ever tried to learn dart. As a javascript developer, I was fascinated by the feature and kinda felt guilty of suffering painful runtime errors when building the code for production. The null safety was introduced to Dart in its 2.0 version. I strongly believe that necessity is the mother of invention, before the introduction of the null safety in Dart, flutter developers had to write a lot of if statements checking if variables had a null value or not. A lot of apps crashed due to variables having unexpected null values. It was really a nightmare and the dart lang maintainers had to come up with a solution and boom THE NULL SAFETY. Null safety simply applies one principle: variables cannot be null at the time of initialization by default unless you explicitly assign them to be nullable. Developers love clarity and thrive in strict environments. Every developer would rather suffer on the code editor than on the build/deployment terminal. You may need a variable to be null, for example, when building an App that fetches data from a backend API asynchronously, you will need the variable to initially be null as it awaits its promise to resolve. The null safety allows the variable to be nullable that is, its value be null until its reassigned or compiled just as null if at all it makes sense in your use case. Null safety reduces a lot of runtime errors and saves us from debugging hell.

//variables are assigned as nullable by putting a question mark after the type annotation

String? name; //nullable
String name; //error , non-nullable variables cannot be null
Enter fullscreen mode Exit fullscreen mode

Sometimes, you may need to have a variable assigned its value later in the program execution flow rather than at the time of initialization. Dart has a solution for that too. The late keyword is used to indicate that the variable is non-nullable and declared without a value with the hope of having its value assigned later in the program. Here is an example;

//non-nullable but initialized without a value

late String name;
print(name);  // error -  the late variable is unassigned at this point

//assign a value 
name = 'Jay';
print(name); // jay
Enter fullscreen mode Exit fullscreen mode

Top comments (0)