Menu
Coddy logo textTech

Basic Null Safety

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

Null safety helps prevent unexpected app crashes by controlling which variables can be empty (null).

By default, variables must contain a value:

void main() {
  String name = 'Dart';
  print(name);  // Outputs: Dart
  
  // This would cause problems:
  // name = null;  // Not allowed
}

Add ? after the type to allow null values:

void main() {
  String? name = 'Dart';
  print(name);  // Outputs: Dart
  
  // Now we can assign null
  name = null;
  print(name);  // Outputs: null
}

You can declare nullable variables of any type:

void main() {
  int? age;  // No initial value, defaults to null
  double? price = 19.99;
  bool? isAvailable = true;
  
  print(age);         // Outputs: null
  print(price);       // Outputs: 19.99
  print(isAvailable); // Outputs: true
  
  // We can change any of these to null
  price = null;
  isAvailable = null;
}

 

Null safety helps protect your app from unexpected crashes that occur when your code tries to use null values in operations.

challenge icon

Challenge

Beginner

Create a Dart program that demonstrates basic null safety using the ? operator:

  1. Declare a String variable named username and set it to null using the null safety operator ? (String?)
  2. Declare an int variable named userAge and set it to null using the null safety operator
  3. Print both variables with labels in the EXACT following format:
Username: null
User age: null

Then:

  1. Assign the value "DartLearner" to the username variable
  2. Assign the value 25 to the userAge variable
  3. Print both variables again with the EXACT same format as before

Your output must match the exact format shown above.

Cheat sheet

By default, Dart variables cannot be null. Add ? after the type to allow null values:

// Non-nullable (default)
String name = 'Dart';

// Nullable with ?
String? name = 'Dart';
name = null;  // Now allowed

You can declare nullable variables of any type:

int? age;           // Defaults to null
double? price = 19.99;
bool? isAvailable = true;

// All can be set to null
price = null;
isAvailable = null;

Try it yourself

void main() {
  // Declare your nullable variables here
  String? username = ?;
  int? userAge = ?;
  
  // Print the initial values with labels
  print("Username: " + username.toString());
  print("User age: " + userAge.toString());
  
  // Assign new values to the variables
  username = ?;
  userAge = ?;
  
  // Print the updated values with the same labels
  print("Username: " + username.toString());
  print("User age: " + userAge.toString());
}
quiz iconTest yourself

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

All lessons in Fundamentals