Null Safety in Dart
Null Safety in Dart#
In this section, you will learn about null safety in the Dart programming language. Null safety helps prevent null reference errors by enforcing strict checks at compile time. This section covers the following topics:
- Null Safety in Dart
- Type Promotion in Dart
- Late Keyword in Dart
- Null Safety Exercise
- Nullable Types and Default Values
- Null Safety with Collections
Null Safety in Dart#
- Definition: Null safety ensures that variables cannot be null unless explicitly declared as nullable.
- Purpose: To eliminate runtime null dereference errors and enhance code reliability.
- Syntax: Use
?
to indicate that a variable or parameter can be null, and!
to assert that a value is non-null.
Example:
void main() {
int? maybeNumber; // Nullable integer
maybeNumber = 10;
// Accessing value safely
if (maybeNumber != null) {
print(maybeNumber + 5); // Outputs: 15
}
}