Menu
Coddy logo textTech

Non-Nullable Types

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

Non-nullable types in Dart are the default for all variables. When you declare a variable without the ? symbol, it must always have a value and cannot be null.

Create a non-nullable String variable:

String name = 'Dart';
print(name);

After executing the above code, the output will be:

Dart

Attempting to assign null to a non-nullable variable causes an error:

// This would cause an error:
// String language = null;

Non-nullable variables must be initialized with a value:

int score = 100;
bool isActive = true;
double price = 9.99;

print('Score: $score, Active: $isActive, Price: $price');

After executing the above code, the output will be:

Score: 100, Active: true, Price: 9.99
challenge icon

Challenge

Beginner

In this challenge, you'll practice working with non-nullable types in Dart. By default, variables in Dart cannot be null unless you explicitly make them nullable using the ? symbol.

Your task is to fix the code by assigning appropriate values to the non-nullable variables that are currently uninitialized.

Expected output:

Name: John
Age: 25
Is active: true
Score: 95.5

Cheat sheet

Non-nullable types in Dart are the default for all variables. They must always have a value and cannot be null.

Declare non-nullable variables with initial values:

String name = 'Dart';
int score = 100;
bool isActive = true;
double price = 9.99;

Non-nullable variables cannot be assigned null:

// This would cause an error:
// String language = null;

Use string interpolation to display variable values:

print('Score: $score, Active: $isActive, Price: $price');

Try it yourself

void main() {
  // These variables are non-nullable and need values
  // TODO: Initialize these variables with appropriate values
  String name;
  int age;
  bool isActive;
  double score;
  
  // This code will print the values
  print('Name: $name');
  print('Age: $age');
  print('Is active: $isActive');
  print('Score: $score');
}
quiz iconTest yourself

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

All lessons in Fundamentals