F

LutterAdda

Null check operator used on a null value

Throughout this demonstration, I'll be guiding you on how to effectively manage the infamous "Null check operator used on a null value" error within Dart or Flutter, all while providing insights into the world of sound and unsound null safety in the Dart programming language.

Let's see an example:

    void main() {
        int? a;
        if(a > 10){
            print('Greater than 10');
        } else{
            print('Less than 10');
        }
    }

In the above code, I have declared a nullable integer variable 'a', and when I used it in a conditional expression it shows :
The operator '>' can't be unconditionally invoked because the receiver can be 'null'.
The error message presented to us is a warning of a potential null value scenario, which, if not handled properly, could cause the program to abruptly terminate with a runtime exception.
To work around this, we can use the null assertion operator, denoted by the '!' symbol, which informs Dart that we are confident that the variable will have a non-null value, allowing us to assign it to a non-nullable type with peace of mind. However, it's important to note that if the value does happen to be null, Dart will throw an exception at runtime, which is why it's generally best to avoid using the null assertion operator unless you are absolutely certain that the expression will not return null.

    void main() {
        int? a;
        if(a! > 10){ // Null assertion operator used
            print('Greater than 10');
        } else{
            print('Less than 10');
        }
    }

After running the above program you will find out that Dart has thrown an error, it will look something like this:
Uncaught TypeError: Cannot read properties of null (reading '$gt')Error: TypeError: Cannot read properties of null (reading '$gt')
This happened because null check operator was used on a null value.

How to handle this error?

To tackle this error we can follow some methods:

Solution 1: Always check nullable values if they are null or not before using it in a expression.

    void main() {
        int? a;
        if(a == null){
            print('The variable is null.');
        } else{
            if(a > 10){
            print('Greater than 10');
            } else{
            print('Less than 10');
            }
        }
    }

This program first check the nullable variable 'a' whether it is null or not. If it is null then the program will skip the else block, if it is not null then the normal flow of the program resumes.

Solution 2: By using default operator '??'

In Flutter, the default operator is represented by the ?? symbol and is used to provide a default value in case a variable is null. Essentially, the ?? operator is shorthand for an if null statement, which checks if a value is null and provides an alternate value to use in case it is. Here's an example to illustrate how the default operator works in Flutter:

    String? name; // variable that may or may not have a value
    String greeting = "Hello, ${name ?? "stranger"}!"; // if name is null, use "stranger" instead
    print(greeting); // Output: "Hello, stranger!"
    

In this example, the ?? operator is used to provide a default value of "stranger" in case the name variable is null. This ensures that the program does not throw a runtime exception due to the use of a null value. Overall, the default operator in Flutter is a convenient way to handle null values and provide default values when necessary, allowing for smoother and more robust application development.

We can also use a shorthand '??=' The null-aware operator ??= provides a shorthand for setting a variable to a default value if it is currently null. It works by checking if the variable on the left-hand side is null, and if so, assigns it the value on the right-hand side.

    String? name; // variable that may or may not have a value 
    name ??= "stranger"; // if name is null, set it to "stranger" instead
    print("Hello, $name!"); // Output: "Hello, stranger!" 
    

In this example, the ??= operator is used to assign the value "stranger" to the name variable only if it is currently null. This provides a convenient shorthand for checking and assigning default values to variables, which can help to make your code more concise and easier to read.

Sound null safety is a feature introduced in Dart 2.12 that aims to provide stronger guarantees around null safety in the language. Specifically, sound null safety seeks to eliminate null reference errors at runtime by ensuring that all variables have a well-defined type that is either nullable or non-nullable.
In a sound null safety system, the compiler can guarantee that a variable of a non-nullable type will never be null, and will emit a compile-time error if there is any risk of a null reference. This can help to eliminate a whole class of runtime errors caused by null references, making code more reliable and easier to maintain.

To achieve sound null safety in Dart, the language introduced the following changes:

-> Non-nullable by default: All variables are non-nullable by default, meaning they cannot be null unless explicitly declared as such using the ? operator.

-> Nullable types: Variables that can be null must be declared with a ? operator after their type, such as int? or String?.

-> Late variables: Variables that are initialized after their declaration can be declared as late, indicating that their value will be assigned before they are used.

-> Null safety analysis: The Dart compiler now performs static analysis on code to determine which variables are nullable and non-nullable, and emits warnings and errors when necessary to ensure soundness.

Overall, sound null safety in Dart provides a stronger guarantee around null safety, helping to eliminate a whole class of runtime errors and make code more reliable and easier to maintain.

To Learn more about null safety please follow this link: Understanding null safety