What is null safety in flutter and dart?

The null safety in Flutter is an important feature that becomes available when Flutter version 2 and above has been released.

No doubt, along with that Dart version must be 2.12.0 or greater than that. We cannot think flutter without dart.

We’ve already checked about that special feature in Dart, and Flutter both in two previous articles.

How do I check if a value is null in flutter and late in Dart and Flutter.

You may check them to have prior ideas about null safety before we proceed any further.

The most prominent feature of null safety feature in flutter and dart, is it completely eliminates the null dereference errors.

For a beginner, this term may seem to be weird.

Let us try to understand the null dereference error first. After that, we’ll understand the importance of null safety in flutter and dart, both.

When we initialize or assign a value to a variable, it points to the memory, which allocates a place for that. However, if we assign null, instead of a valid value, what happens?

The null pointer dereference takes place.

A pointer with a valid value, was supposed to point to a valid memory area. On the contrary, it uses a value of NULL.

As a result, programmer’s assumption fails. And, quite naturally, compiler starts complaining.

How do we make flutter null safe?

To make flutter null safe, we can use late keyword in our custom classes. Or we can use “?” operator.

Let us check a code first.

class SoundNullSafety extends StatelessWidget {
  const SoundNullSafety({Key? key}) : super(key: key);

  final String aString = 'Beginning Flutter with Dart'; // Cannot be null.
  final String? aNullableString = null; // Can be null.
...
// code is incomplete for brevity

Watch the “?” operator we’ve used after String while we assign the value to NULL.

Now, inside a text widget, we can reference that “aNullableString”.

Sound null safety in Flutter
Sound null safety in Flutter

In Dart though, we can use it in a different way.

Let’s see the code first in in our library classes, in lib folder. You may consult the respective GitHub repository.

String getFileName() {
  return 'String';
}

void Foo() {
  print('buzz');
}

// var i = 42;
var i; // Inferred to be an int.
String name = getFileName();
final b = Foo();

int? intCouldBeNullable;

We run the code inside bin folder.

import 'package:my_cli/null_safety_check.dart' as null_safety_check;

void main(List<String> arguments) {
  print(null_safety_check.i);
  print(null_safety_check.name);
  null_safety_check.b;
  var x = null_safety_check.intCouldBeNullable = null;
  print(x);
}

Let’s take a look at the output first, then we will discuss the code.

null
String
buzz
null

In the first case, we’ve not assigned any value to the variable i. And in the last case, we’ve told the compiler that maybe we’re going to assign a value of null.

In the last case, we’ve taken help from the “?” operator.

What is null safety in programming?

The basic paradigm of null safety or you may call void safety in object oriented programming assures that we should never have any object reference that will have null or void values.

Let us consider more code in Dart before we jump in to watch another example in Flutter.

class BarValueProvider {
  late final bool _cond = true;
  bool get cond => _cond;
  int _returnValue() {
    return 43;
  }

  late final int _bar = _returnValue();
  int get buzz => _bar;

  int? testCondition(cond) => cond ? 1 : null;
}

Let us create a reference variable and instantiate the above class. And, after that, firstly we’ll pass value false as parameter of the method testCondition().

What will happen?

Firstly, we’ve used “?” operator while returning the method. Secondly, moreover, we have used late keyword while declaring the private property that is going to be passed through the method.

Let’s pass false first, then we pass true.

import 'package:my_cli/more_null_safety.dart';

void main() {
  print('Calling constructor...');
  var provider = BarValueProvider();
  print('Getting value...');
  print('The value is ${provider.buzz}!');
  print(provider.testCondition(false));
  print(provider.testCondition(true));
}

As expected, false will provide us a value of null. And true will provide us an integer 1, which stands for boolean true.

Calling constructor...
Getting value...
The value is 43!
null
1

We’ve moved the nullable testCondition() method inside the class after adding late keyword to the declaration of the private property _cond.

By using late keyword we’ve assured the Dart compiler that we’ll never allow that private property to be NULL.

However, later, we’ll use “?” operator to tell the compiler that it can be null. As a result, the boolean value false has provided a value of null.

Null safety in Flutter

Flutter latest version 2.5 has made it sure that it’ll maintain sound null safety. That’s why, in most places we see the “?” operator.

If we break the rule, it warns us before we run the flutter app.

Suppose we have a Student class in our models folder and we declare that one property can be null.

class Student {
  final String id;
  final String name;
  final String? studentClass;
  const Student(
    this.id,
    this.name,
    this.studentClass,
  );
}

Later, when we map that list items in our widget, it gives us error like this:

Flutter null safety error before compilation
Flutter null safety error before compilation

It says that we cannot assign a null value instead of a String value.

After correcting the error while we run the app, it tells us Flutter is running with sound null safety.

Running with sound null safety
Running with sound null safety

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Technical blog

Twitter

Comments

3 responses to “What is null safety in flutter and dart?”

  1. […] a big difference with other providers. Since, the provided value might take time to appear, it must not be null. That’s why, the FutureProvider has a required parameter “initialdata”, which is […]

  2. […] Because Color isnt assigned yet it can be null. Dart has nullsafety so the question mark implies the value can be null. See this link for more details: https://sanjibsinha.com/null-safety-in-flutter-dart/ […]

  3. […] Because Color isnt assigned yet it can be null. Dart has nullsafety so the question mark implies the value can be null. See this link for more details: https://sanjibsinha.com/null-safety-in-flutter-dart/ […]

Leave a Reply