Dart| Flutter sound null safety

Abhishek
3 min readSep 5, 2021

I recently moved to dart SDK version to 2.12.0(flutter 2.0) from 2.10.0 and I was amazed by features added in new SDK .Sound null safety is a major new productivity feature that helps you avoid null exceptions, a class of bugs that are often hard to spot. As an added bonus, this feature also enables a range of performance improvements.https://dart.dev/null-safety

Why Dart| flutter need null safety?

Dart is a type-safe language. This means that when you get a variable of some type, the compiler can guarantee that it is of that particular type. But type safety by itself doesn’t guarantee that the variable is not null.So ,Dart team came up with few core design principles to handle all null safety features implementation and migration strategy for old apps.

  1. Non-nullable by default :Unless you explicitly tell Dart that a variable can be null, it will be considered non-nullable.Let’s see some non-nullable variables, declared in different ways.
In null-safe Dart, none of these can ever be null.

If you try to set a value of any of these variables to null a thousand lines later, you’ll get a static analysis error and red squiggly lines, and your program will refuse to compile.e.g.

Non-nullable can’t be assigned as null.

2.Nullable variables: If you want to have variable as nullable you can use “ ? “ in after data type as :

Nullable variable declaration

Null aware operators

  1. if null(??):how it works ,let’s say we have variable name as nullable string and we want to use it for operation ‘ ?? ’ can be used to check if left side of variable is null or not ,if left left side is null then right side value will be assigned to userName.
use of ??

2. null aware assignment(??=): As in previous example name variable is checked as null or not then value is assigned ,but thats a extra step you can skip and use it as :

use of ??=

3. null aware access (?.):For Example in this code snippet

use of ?.

name is nullable and we want to verify it before calculation length, we have to use ‘ ? ’after variable name (Note: don’t use “!” to check in dart).

4. null aware cascade(?..) : let’s assume we have class UserExtended with nullable property as name and address and we want to use it in another class we can use “?..” as :

use of ?..

That’s all for today. Thank you for reading this article. Hope it helps you to learn more about how the migrate and to implement null safety for all your Flutter projects. If you have any suggestions or questions, welcome to leave a comment below. See you next time bbyeeee✌️.

“Lets Make the world a better place” ✌️

--

--