Menu
Coddy logo textTech

Null Assertion Operator

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

The null assertion operator (!) tells Dart that a nullable variable is definitely not null at that point in the code. It forces Dart to treat a nullable type as non-nullable.

Create a nullable string variable:

String? name = 'Dart';

Use the null assertion operator to treat it as non-nullable:

String nonNullableName = name!;
print(nonNullableName);

After executing the above code, the output will be:

Dart

Be careful! If the variable is actually null, your program will crash:

String? language = null;
// String nonNullable = language!; // This would crash at runtime
challenge icon

Challenge

Beginner

In this challenge, you'll practice using the Null Assertion Operator (!) in Dart. This operator tells Dart that a nullable variable is definitely not null at a specific point in your code.

Complete the code below to use the null assertion operator to convert the nullable username variable to a non-nullable string that can be assigned to displayName.

Expected output:

Welcome, DartLearner!

Cheat sheet

The null assertion operator (!) tells Dart that a nullable variable is definitely not null at that point in the code. It forces Dart to treat a nullable type as non-nullable.

String? name = 'Dart';
String nonNullableName = name!;
print(nonNullableName); // Output: Dart

Warning: If the variable is actually null, your program will crash at runtime:

String? language = null;
// String nonNullable = language!; // This would crash

Try it yourself

void main() {
  // This nullable String variable already has a non-null value
  String? username = 'DartLearner';
  
  // TODO: Use the null assertion operator (!) to convert username
  // from a nullable String to a non-nullable String
  // so it can be assigned to displayName
  String displayName;
  
  // This will display the welcome message
  print('Welcome, $displayName!');
}
quiz iconTest yourself

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

All lessons in Fundamentals