Learn/Dart for Flutter/Null Safety

Null Safety

Write safer code with Dart null safety and null-aware operators

5 min~5 min read+30 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Choosing Between ?, ??, ?., !, and late
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Null Safety in Dart

Null safety prevents null pointer exceptions, which are crashes caused by using a variable that was never assigned a value.

In Dart, variables are non-nullable by default. You must explicitly opt in to nullable types using ?.

dart
1// Non-nullable - must always have a value
2String name = 'Alice';
3int age = 25;
4
5// Nullable - can hold null
6String? nickname = null; // OK ✓
7int? score; // Also null by default ✓
8
9// Error: non-nullable cannot be null
10// String city = null; // ❌ Compile error
11
12// ── Null-aware operators ──
13String? user;
14
15// ?. - safe access (returns null instead of crashing)
16print(user?.toUpperCase()); // null
17
18// ?? - null coalescing (fallback value)
19String display = user ?? 'Guest';
20print(display); // Guest
21
22// ??= - assign only if null
23user ??= 'DefaultUser';
24print(user); // DefaultUser
25
26// ! - null assertion (crash if null - use carefully!)
27String definitelySet = 'Hello';
28String? maybeSet = definitelySet;
29print(maybeSet!.length); // 5
dart
1// ── late keyword ──
2// For non-nullable variables initialized after declaration
3class ProfileScreen extends StatefulWidget {
4 late String userId; // Will be set before first use
5
6 void init(String id) {
7 userId = id;
8 }
9}
10
11// Lazy initialization with late
12late final List<String> data = _loadData(); // Only computed when first accessed
13
14List<String> _loadData() => ['item1', 'item2'];

Golden Rule

💡 Golden Rule

Prefer using ?? and ?. over the ! operator. The ! operator defeats null safety. If you use it on a null value, your app crashes at runtime. Always provide a fallback with ?? when possible.

Choosing Between ?, ??, ?., !, and late

Use this mental model:

  • '?': value may truly be absent
  • '??': provide safe fallback value
  • '?.': safely read from maybe-null object
  • '!': only when you are 100% certain value is non-null
  • 'late': value will be initialized before first use

Most production crashes from null safety happen because ! is used to silence compiler warnings instead of fixing data flow.

Null Safety Upgrade Drill

  • Mark only truly optional values as nullable.
  • Replace direct property access with ?. where needed.
  • Add ?? fallback values for user-facing strings.
  • Remove unnecessary ! after improving control flow.

This Lesson In Simple Words

Write safer code with Dart null safety and null aware operators. Dart is the language behind Flutter, and clear Dart code makes your Flutter UI easier to maintain.

Your level focus

Build confidence with basics first; speed comes later.

One practical habit

Prefer readable names, explicit intent, and async/await over deeply nested callbacks.

Deep Understanding Guide

Why this lesson matters

When Dart basics are weak, state bugs, null crashes, and async confusion increase quickly.

Study flow for better retention

  1. Read one section, run one tiny example, then explain the idea in your own words.
  2. Treat each Dart concept as a building block for widgets, services, and tests you will write later.
  3. If you can teach it in 45 seconds without notes, you understood it.

Common Mistakes To Avoid

  • Ignoring null safety and forcing values with ! without checking data flow.
  • Writing long functions that mix validation, transformation, and side effects together.
  • Using dynamic where a proper type would catch mistakes earlier.
  • Catching broad errors without keeping useful context for debugging.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write a small pure function and test it with edge cases.
  • Convert one callback-based snippet to async/await with proper error handling.
  • Refactor a long function into smaller helper methods with clear names.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does adding ? after a type (e.g. String?) mean in Dart?".

Quick Glossary

  • null safety: Dart type system feature that prevents null reference errors.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "Null Safety" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Ignoring null safety and forcing values with ! without checking data flow.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does adding ? after a type (e.g. String?) mean in Dart?

String? means the variable is nullable. It can hold either a String value or null. Without ?, the variable can never be null.

What does the ?? operator return?

The ?? operator is null coalescing. `a ?? b` returns a when a is not null, otherwise returns b as a fallback.

What does user?.name return when user is null?

The ?. operator (null-aware access) safely returns null instead of crashing when the object is null.

When should you use the late keyword?

late tells Dart that a non-nullable variable will be assigned before first use, bypassing the requirement to initialize at declaration.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue