Files

2.0 KiB

Null Safety in Dart: A Comprehensive Guide

Null safety is a feature in Dart that helps prevent null reference exceptions, making your code more robust and less prone to runtime errors.

1. Nullable and Non-nullable Types

In Dart with null safety, types are non-nullable by default. To make a type nullable, add a question mark (?) after the type.

Example:

String nonNullableString = "Hello"; // Can't be null
String? nullableString = null; // Can be null

int nonNullableInt = 42; // Can't be null
int? nullableInt = null; // Can be null

2. The ?, !, and ?? Operators

  • ?: Null-aware operator
  • !: Null assertion operator
  • ??: Null-coalescing operator

Example:

String? nullableString = null;

// Null-aware operator
print(nullableString?.length); // Prints null

// Null assertion operator (use with caution!)
// print(nullableString!.length); // Throws exception if nullableString is null

// Null-coalescing operator
String nonNullString = nullableString ?? "Default";
print(nonNullString); // Prints "Default"

3. Late Variables

The late keyword allows you to declare a non-nullable variable that's initialized after its declaration.

Example:

class Person {
  late String name;

  void setName(String newName) {
    name = newName;
  }
}

void main() {
  final person = Person();
  person.setName("Alice");
  print(person.name); // Prints "Alice"
}

4. Required Named Parameters

Use the required keyword to make named parameters non-nullable and required.

Example:

void printPersonInfo({required String name, required int age}) {
  print("Name: $name, Age: $age");
}

void main() {
  printPersonInfo(name: "Bob", age: 30); // OK
  // printPersonInfo(name: "Charlie"); // Compile-time error: missing required parameter 'age'
}

Conclusion

Null safety helps catch null-related errors at compile-time rather than runtime, leading to more reliable code. Practice using these features to write more robust Dart and Flutter applications.