Basics

Dart Null Safety

Null Safety in Dart

Dart null safety uses ? and ! for safe nullable types.

Introduction to Dart Null Safety

Dart null safety is a feature that prevents null dereference errors in your code. It leverages the ? and ! operators to handle nullable types safely, ensuring your applications run smoothly without unexpected crashes.

Nullable and Non-Nullable Types

In Dart, every variable is non-nullable by default, which means it cannot contain a null value. To allow a variable to be null, you need to use the ? operator. This signals that the variable can hold a null value.

Using the '?' Operator

The ? operator is used to indicate that a variable can be nullable. This prevents runtime errors by requiring you to handle null cases explicitly.

The '!' Operator for Null Assertion

The ! operator, known as the null assertion operator, is used to tell the Dart compiler that a variable is non-null, even if it could be nullable. Use this operator cautiously as it can lead to runtime errors if the variable is actually null.

Late Initialization

Dart provides a late keyword for lazy initialization of variables. This is useful when you are sure a variable will be initialized before it is used, but not at the point of declaration.

Conclusion

Null safety in Dart makes your code more robust and less prone to errors. By understanding how to use ? and !, as well as the late keyword, you can write safer and more reliable Dart applications.