Menu
Coddy logo textTech

Null-aware Operator

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

The null-aware operator (??) returns the left expression if it's not null, otherwise returns the right expression.

void main() {
  String? name = 'Dart';
  String displayName = name ?? 'Guest';
  
  print('Hello, $displayName!');
}
void main() {
  String? name = null;
  String displayName = name ?? 'Guest';
  
  print('Hello, $displayName!');
}
void main() {
  int? score;  // No initial value, defaults to null
  int displayScore = score ?? 0;
  
  print('Your score: $displayScore');
  
  // Later in the program, score gets a value
  score = 100;
  displayScore = score ?? 0;
  
  print('Your updated score: $displayScore');
}
challenge icon

Challenge

Easy

Create a program that demonstrates the null-aware operator (??) in Dart:

  1. Declare a nullable String variable named username and set it to null
  2. Declare a nullable int variable named userAge and set it to null
  3. Use the null-aware operator to assign a default value of "Guest" to a new variable displayName if username is null
  4. Use the null-aware operator to assign a default value of 18 to a new variable displayAge if userAge is null
  5. Print the values with the EXACT following format:
Username: Guest (default value used)
Age: 18 (default value used)

Then:

  1. Update username to "DartUser"
  2. Update userAge to 25
  3. Repeat steps 3 and 4 with the updated values
  4. Print the values with the EXACT following format:
Username: DartUser (original value used)
Age: 25 (original value used)

Cheat sheet

The null-aware operator (??) returns the left expression if it's not null, otherwise returns the right expression.

String? name = null;
String displayName = name ?? 'Guest';  // Returns 'Guest' since name is null

int? score = 100;
int displayScore = score ?? 0;  // Returns 100 since score is not null

Try it yourself

void main() {
  // Declare nullable variables
  String? username = _;
  int? userAge = _;
  
  // Use null-aware operator for default values
  String displayName = username ?? _;
  int displayAge = userAge ?? _;
  
  // Print initial values
  print("Username: $displayName (default value used)");
  print("Age: $displayAge (default value used)");
  
  // Update variables
  username = _;
  userAge = _;
  
  // Use null-aware operator again
  displayName = username _ "Guest";
  displayAge = userAge _ 18;
  
  // Print updated values
  print("Username: $displayName (original value used)");
  print("Age: $displayAge (original value used)");
}
quiz iconTest yourself

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

All lessons in Fundamentals