Skip to content

Null Safety

If you have been programming any amount of time, you’ve provably had a program crash because you tried to call a method on a variable you didn’t realized was a null

void main() {
String name;
print(name.length);
}
Uncaught TypeError: Cannot read properties of null (reading 'get$length')
Error: TypeError: Cannot read properties of null (reading 'get$length')

Null safety enables the compiler to help you find and fix those bugs before you run the code.

  • Goal is not to eliminate null , the absence of data is like part of life right?
  • some people don’t have middle names, some attributes doesn’t have values, So null is a great way to model data you don’t have
  • it has short little syntax, many developers familiar with it, so null is not a problem, calling the methods on null is
  • We right some code
  • Expect it to be worked
  • Run our program
  • On a good day it works on bad day we get an exception
  • and we repeat

Productivity of a developer will increase if we ease done this iterations

So we have introduced non nullable type by default which means Null Safety

In dynamically types types language , I might have to run my program and get an exception before I realised the mistake, but in Dart type checker immediately tells me there’s something fishy here

  • but if you add some runtime features in language → potential to increase set of things user can do
  • Type systems don’t work that way, we mostly get compile errors which prevent your code from running

We can make type check dance the way want→ lets say to check even or odd number

but it doesn’t help us to build apps right

Static analysis helps

  • to check every possible way our code could executes
  • every path it could be taken
  • the value variable might have
  1. change seBackgroundColor parameter as nullable and call is nullsafe
    1. assign before accessing the value
    2. check is it is null or not
  2. change seBackgroundColor parameter as nullsafe and call is nullable
    1. assign before accessing the value
    2. Random().nextBool() to show case control flow
    3. ??