Intro to Null Safety
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 23 of 110.
One of the most common sources of bugs in programming is attempting to use a value that doesn't exist. In Dart, this special "absence of value" is represented by null. Dart's null safety feature helps you catch these errors before your code even runs.
Without null safety, any variable could potentially be null, leading to runtime crashes when you try to use it:
// In older Dart (without null safety)
String name; // Could be null!
print(name.length); // Crash if name is nullWith null safety enabled (Dart 2.12+), the compiler distinguishes between variables that can hold null and those that cannot. By default, variables are non-nullable - they must always contain a valid value:
String name = 'Alice'; // Must have a value
print(name.length); // Safe - name is never nullThe compiler will refuse to compile code where a non-nullable variable might be null. This shifts error detection from runtime to compile time, making your programs more reliable. In the upcoming lessons, you'll learn how to declare nullable types when you genuinely need them, and the operators Dart provides for working with potentially null values safely.
Challenge
EasyLet's build a simple contact card system that demonstrates the importance of non-nullable variables. You'll create a system where every contact must have valid, guaranteed information.
You'll organize your code into two files:
contact.dart: Define aContactclass that represents a person's contact information. Since we're working with null safety, every field must have a valid value - no missing data allowed! Your class should have:- A
String firstNamefor the contact's first name - A
String lastNamefor the contact's last name - A
String emailfor the contact's email address - An
int phoneDigitsfor the number of digits in their phone number - A constructor that takes all four values
- A getter
fullNamethat returns the first and last name combined with a space between them - A
displayCard()method that prints the contact's information
- A
main.dart: Import your contact class and create two contacts to demonstrate that all fields are guaranteed to have values:- Create a contact with first name
'Emma', last name'Wilson', email'emma@mail.com', and phone digits10 - Create a contact with first name
'James', last name'Brown', email'james@work.com', and phone digits11 - Call
displayCard()on each contact in the order listed above
- Create a contact with first name
The displayCard() method should print in this exact format:
--- Contact Card ---
Name: [fullName]
Email: [email]
Phone digits: [phoneDigits]Notice how every variable must be initialized with a real value - this is null safety in action! The compiler guarantees that when you access fullName, email, or any other field, it will always contain valid data.
Expected output:
--- Contact Card ---
Name: Emma Wilson
Email: emma@mail.com
Phone digits: 10
--- Contact Card ---
Name: James Brown
Email: james@work.com
Phone digits: 11Cheat sheet
Dart uses null safety to prevent bugs caused by using values that don't exist. The special value null represents the absence of a value.
With null safety enabled (Dart 2.12+), variables are non-nullable by default - they must always contain a valid value:
String name = 'Alice'; // Must have a value
print(name.length); // Safe - name is never nullThe compiler prevents code from compiling if a non-nullable variable might be null, shifting error detection from runtime to compile time.
Try it yourself
import 'contact.dart';
void main() {
// TODO: Create first contact with:
// - first name: 'Emma'
// - last name: 'Wilson'
// - email: 'emma@mail.com'
// - phone digits: 10
// TODO: Create second contact with:
// - first name: 'James'
// - last name: 'Brown'
// - email: 'james@work.com'
// - phone digits: 11
// TODO: Call displayCard() on each contact in order
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor