7. Null Safety in Dart

Null Safety In Dart

Null Safety is the safety enforing to prevent errors that result from unintentional access of variables set to null. When a method expects an integer receives null, application causes a runtime error, which is a null dereference error to debug so null safety there.

Null Safety through Examples

With null safety, none of the variables in the following code can be null.

void main(){
var i = 24; // inferred to be an int.
String name = getFilename();
final b = Foo;
}

To be a variable null We can do like this :-

int? q = null; //valid

All the uninitialized variables have default value null in all versions of dart:

int? a; // the initial value of a is null

Null Safety Principles

Dart supports null safety using two core design principles:

  • Non-nullable by default: Unless you explicitly tell Dart that a variable can be null, it’s considered non-nullable like above.
  • Fully sound: Dart’s null safety is sound, which enables compiler optimizations.