Menu
Coddy logo textTech

Null-aware Access

Part of the Fundamentals section of Coddy's Dart journey — lesson 29 of 94.

The null-aware access operator (?.) safely accesses properties on potentially null objects, preventing runtime errors.

void main() {
  String? name = 'Dart';
  int? length = name?.length;
  
  print('Name: $name');
  print('Length: $length');
}

With null values, it returns null instead of crashing:

void main() {
  String? name = null;
  int? length = name?.length;
  
  print('Name: $name');
  print('Length: $length');
}
challenge icon

Challenge

Easy

Create a Dart program that demonstrates the null-aware access operator (?.) with a game character:

  1. Create a nullable String variable called playerName and set it to null
  2. Create a nullable int variable called playerScore and set it to 100
  3. Use the null-aware access operator (?.) to get the length of the playerName and store it in a variable called nameLength
  4. Print the following message: Player name length: X (where X is the value of nameLength)
  5. Update playerName to "Champion"
  6. Use the null-aware access operator again to get the updated length and store it in nameLength
  7. Print the updated message: Player name length: X (where X is the new value)
  8. Print the player's score with this format: Player score: 100

Cheat sheet

The null-aware access operator (?.) safely accesses properties on potentially null objects, preventing runtime errors.

When the object is not null, it returns the property value:

String? name = 'Dart';
int? length = name?.length; // Returns 4

When the object is null, it returns null instead of crashing:

String? name = null;
int? length = name?.length; // Returns null

Try it yourself

void main() {
  // Declare your nullable variables here
  String? playerName = _;
  int? playerScore = _;
  
  // Get the length of playerName using ?. operator
  int? nameLength = playerName_.length;
  
  // Print the initial name length
  print("Player name length: ${nameLength}");
  
  // Update the playerName
  playerName = _;
  
  // Get the updated length using ?. operator
  nameLength = playerName_.length;
  
  // Print the updated name length
  print("Player name length: ${nameLength}");
  
  // Print the player's score
  print("Player score: ${playerScore}");
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals