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
BeginnerCreate a Dart program that demonstrates basic null safety using the ? operator:
- Declare a String variable named
usernameand set it tonullusing the null safety operator?(String?) - Declare an int variable named
userAgeand set it tonullusing the null safety operator - Print both variables with labels in the EXACT following format:
Username: null
User age: nullThen:
- Assign the value
"DartLearner"to theusernamevariable - Assign the value
25to theuserAgevariable - 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 allowedYou 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());
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Comparison OperatorsLogical ANDLogical ORLogical NOTType Test OperatorsRecap - Making Comparisons7Working with Strings
String ConcatenationString InterpolationMulti-line StringsString PropertiesBasic String Methods10Collections - Maps Basics
What are Maps?Creating a MapAccessing Values by KeyKey-Value PairsGetting Map SizeGetting KeysGetting ValuesChecking if a Key Exists13Null Safety In Depth
Understanding NullNullable TypesNon-Nullable TypesNull Assertion OperatorLate InitializationRecap - Handling Null Safely16Fundamentals Challenges
Challenge: List of calculationChallenge: Sum of numbersChallenge: Find product2Variables and Basic Data Types
What are Variables?StringsIntegers (int)Doubles (double)Booleans (bool)Type Inference with 'var'Final VariablesConstant VariablesNaming ConventionsBasic Null SafetyRecap - Declaring Variables8Control Flow - Loops
The 'for' LoopThe 'while' LoopThe 'do-while' LoopUsing 'break' in LoopsUsing 'continue' in LoopsRecap - Repeating Code3Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorIncrement and DecrementAssignment ShortcutsRecap - Simple Calculations6Control Flow - Decision Making
The 'if' StatementThe 'else' StatementThe 'else if' StatementRecap - Simple DecisionsNested 'if' StatementsThe 'switch' Statement9Collections - Lists Basics
What are Lists?Creating a ListAccessing by IndexGetting List LengthAdding ElementsRemoving ElementsChecking if a List is EmptyIterating Over a List12Functions Advanced
Optional Positional ParametersNamed ParametersRequired Named ParametersDefault Parameter ValuesRecap - Function Parameters15Project: Simple Calculator
Setting UpDeclaring Number