What does non-nullable by default mean in Dart?

“Non-nullable by default” is a language feature introduced in Dart 2.12. It means that starting from Dart 2.12, all variable types, including primitive types and user-defined classes, are considered non-nullable by default, unless explicitly marked as nullable using the ? suffix.

In simple terms, any variable that is not explicitly declared as nullable using the ? is guaranteed to hold a non-null value, and the Dart compiler enforces this rule during static analysis. This feature was introduced to improve code safety and help prevent common null-related errors like null pointer exceptions.

Here are the key points to understand about non-nullable by default in Dart:

  1. Non-Nullable Types: Variables without the ? suffix are non-nullable by default. For example:
int age = 25; // Non-nullable type 'int'
String name = 'John'; // Non-nullable type 'String'
  1. Nullable Types: To declare a variable that can hold a null value, you must explicitly add the ? suffix after the type. For example:
int? nullableAge = null; // Nullable type 'int?'
String? nullableName = null; // Nullable type 'String?'
  1. NonNull Assertion Operator (!): If you are certain that a nullable variable is non-null at a specific point in the code, you can use the non-null assertion operator ! to tell the Dart compiler that the variable will not be null at that point. However, using ! incorrectly can lead to null pointer exceptions, so use it with caution.
String? nullableName = 'John';
String nonNullableName = nullableName!; // Using the non-null assertion operator.
  1. Null Safety: Non-nullable by default is part of Dart’s null safety feature, introduced in Dart 2.12. With null safety, the Dart compiler performs extensive static analysis to help ensure that null-related errors are caught at compile-time rather than causing runtime exceptions.

Overall, non-nullable by default is a powerful feature in Dart that promotes safer code by reducing the risk of null pointer exceptions. By enforcing non-null guarantees at compile-time, it allows developers to write more robust and reliable Dart applications.

error: Content is protected !!