Null Safety with Flutter 2.0

Astha Nayak
5 min readJun 27, 2021

--

Null Value Safety is undoubtedly a blessing in disguise for all the developers. But for starters, understanding and implementing it can be overwhelming. One has to first understand what does Null Safety mean and how to use it for reducing the run-time errors while programming,

Programmers like statically typed languages because they enable the type checker to find mistakes in code at compile-time, usually right in the IDE. The sooner you find a bug, the sooner you can fix it. When language designers talk about “fixing null reference errors”, they mean enriching the static type checker so that the language can detect mistakes like the variable not being initialised.

What does Null Safety actually mean? How does it look while coding?

It is the new Dart Upgrade that added a new feature called compile-time null safety. The idea is to force all variables to be initialized with some value. In that case, there won’t be any runtime error that causes by null value dereferencing. This is called “Null Safety”.

We can use DartPad to understand how this works. Use this small snippet of code in your Dartpad -

There is a small toggle button in the bottom-left corner of the page labelled as ‘Null Safety’. Something like this -

Null Safety Toggle Button

First, let’s disable this button, i.e. the code we write won’t be safe from the null value.

We can see that there are no compile-time errors as we put in the code. But what happens once we run it!

We get a run time error due to the null value of the string. This is something that might cause your flutter app to crash with you having no hint of this blunder while writing and checking your code. This might be heavily problematic for large code bases as it is difficult to track numerous variables.

This is where ‘Null Safety’ comes in handy and will rescue you. Let’s enable the Null Safety and check how it pans out.

As we see here, When we enable null safety in DartPad, the compiler will throw an error stating that our variable is not initialized. The program will not compile and run. This is very handy! Because it raises errors before we run the program so developers would notice and fix them before handling it to the end-user.

Benefits of NULL SAFETY

Dart code is `SAFE` by default. If we write new Dart code and don’t use any explicitly unsafe features, it never throws a null reference error at runtime. All possible null reference errors are caught statically. If you want to defer some of that checking to runtime to get greater flexibility, you can, but you have to choose that by using some feature that is textually visible in the code, something like addressing the variables as dynamic without specifying any strong data type. Quoting from the documentation

‘ We aren’t giving you a life jacket and leaving it up to you to remember to put it on every time you go out on the water. Instead, we give you a boat that doesn’t sink. You stay dry unless you jump overboard.’

Null errors are absolutely normal. A view of GitHub Issues in Flutter and Dart prompts a large number of issues brought about by sudden nulls in Dart code, and surprisingly many submit attempting to fix those issues. The null safety included code makes these issues disappear with null safety, we can reason about our code with more certainty. Not any more troublesome runtime null dereferencing mistakes. All things considered, we get static mistakes as we code which are much easier to solve than run-time errors.

Sound null safety kills bugs brought about by nulls. It makes data-types in our Dart code non-nullable naturally. It implies that factors can’t contain null except if we say they can.

How to enable NULL SAFETY in Flutter

Now that we have understood what NULL SAFETY basically means, let’s get to know how we could maximise its benefits without causing many hindrances in our development process.

Before we go much further, we need to understand that at the present moment, switching to Null Safety is purely in our hands, applications and packages will possibly run with null safety if their base Dart SDK constraint is, in any event, a Dart 2.12

Migrating existing code-base to NULL Safety

  • Check if your dependencies are compatible — I believe that migrating code through and through, with the help of the dependency diagram is very essential. For example, if C depends upon B which depends upon A, migrate A to null safety first, by then B, then C.
  • Use a migration tool — The migration tool takes a package of null-unsafe Dart code and converts it to sound null safety. We can guide the tool’s conversion by adding hint markers to your Dart code. Before starting the tool, make sure we’re ready:

Use the latest release of the Dart SDK.

Use dart pub outdated --mode=null-safety to make sure that all dependencies are null safe.

Start the migration tool by running the dart migrate command in the directory that contains the package’s pubspec.yaml file.

  • Statically analyze your migrated code — Once the code is migrated with the help of the tools, we cross over and check for any anomaly. We can use dart analyze for this purpose.
  • Test it out — Run all the tests that we would have written earlier for the validity of the code. These tests should still work as the logic and intent of the code hasn’t changed context.

Covering all these steps may take time, but it is an assured reward as it brings with itself ease to code and relevancy with the latest flutter updates as NULL SAFETY is the revolution. We should realize that while doing refactoring for null safety we can depend on the compiler. It makes the cycle very straightforward. I accept that migrating our code to null safety is preferably compulsory over discretionary. This might seems tiring at the present moment but it will save you numerous long stretches of work thereafter.

I hope this blog will provide you with ample information on Null Safety Support For Flutter & Dart. Do comment if you have any suggestions. Thank you for reading.

--

--

Astha Nayak

Mobile Application Developer | CS Undergrad | Community Leader