Learn/Dart for Flutter/Dart 3: Records, Patterns & Sealed Classes

Dart 3: Records, Patterns & Sealed Classes

Master modern Dart 3 language features: records, pattern matching, destructuring, and exhaustive sealed classes

12 min~7 min read+50 FX

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

Table of Contents

  1. 1. 1. Records: Returning Multiple Values Without Boilerplate
  2. 2. How Records Work
  3. 3. Pattern Destructuring
  4. 4. 2. Pattern Matching & Switch Expressions
  5. 5. Switch Statements vs Switch Expressions
  6. 6. Guard Clauses with `when`
  7. 7. 3. Sealed Classes & Exhaustive Safety
  8. 8. Why This Matters for Flutter UI
  9. 9. This Lesson In Simple Words
  10. 10. Your level focus
  11. 11. One practical habit
  12. 12. Deep Understanding Guide
  13. 13. Why this lesson matters
  14. 14. Study flow for better retention
  15. 15. 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

Dart 3: Records, Patterns & Sealed Classes

Dart 3 introduced the biggest evolution to the Dart language since Sound Null Safety. If you are building Flutter applications today, mastering Records, Pattern Matching, and Sealed Classes will make your code significantly more concise, expressive, and immune to entire categories of runtime bugs.

In this lesson, we will break down each feature with simple mental models and real-world Flutter examples.

1. Records: Returning Multiple Values Without Boilerplate

Prior to Dart 3, if a function needed to return more than one piece of data (for example, coordinates x and y, or a user's name and age), you had two imperfect options:

  1. Return a Map<String, dynamic> — loose typing where typos cause runtime bugs.
  2. Create a full custom class with constructors and fields — heavy boilerplate for simple pairs.

How Records Work

A Record is an anonymous, immutable, type-safe aggregate of values.

// Positional Record:
(double, double) getCoordinates() {
  return (37.7749, -122.4194);
}

// Named Record:
({String name, int age}) getUserInfo() {
  return (name: 'Sarah', age: 26);
}

Pattern Destructuring

Instead of accessing fields with index syntax, you can unpack them in a single readable line:

final (lat, lng) = getCoordinates();
print('Latitude: \$lat, Longitude: \$lng');

final (name: userName, age: userAge) = getUserInfo();
print('User: \$userName is \$userAge years old');

Record Equality

💡 Record Equality

Records have built-in value equality! Two records with identical field values are automatically considered equal (== returns true) without writing custom hashcode or equals methods.

2. Pattern Matching & Switch Expressions

Dart 3 revolutionized switch from a verbose statement with manual break; lines into a high-powered expression that returns values directly.

Switch Statements vs Switch Expressions

// OLD WAY (Dart 2 statement):
String getStatusMessage(int statusCode) {
  switch (statusCode) {
    case 200:
      return 'Success';
    case 404:
      return 'Not Found';
    case 500:
      return 'Server Error';
    default:
      return 'Unknown Status';
  }
}

// MODERN DART 3 WAY (Switch Expression):
String getStatusMessage(int statusCode) => switch (statusCode) {
  200 => 'Success',
  404 => 'Not Found',
  500 => 'Server Error',
  _ => 'Unknown Status', // wildcard fallback
};

Guard Clauses with when

You can attach conditions to patterns using when:

String formatAge(int age) => switch (age) {
  < 0 => 'Invalid age',
  >= 0 && < 13 => 'Child',
  >= 13 && < 20 => 'Teenager',
  _ when age >= 65 => 'Senior Citizen',
  _ => 'Adult',
};

3. Sealed Classes & Exhaustive Safety

One of the most powerful patterns in modern Flutter state management is the Sealed Class.

When you mark a class with the sealed modifier:

  1. It cannot be directly instantiated (it is implicitly abstract).
  2. All of its subclasses must be declared in the exact same library file.
  3. The Dart compiler knows every single possible subclass that exists in the entire universe!

Why This Matters for Flutter UI

When you use a switch expression over a sealed class hierarchy, Dart forces exhaustiveness. If you handle Loading and Success, but forget Error, the compiler will refuse to compile your code until you handle the missing state!

dart
1// sealed_auth_state.dart
2import 'package:flutter/material.dart';
3
4// Sealed state hierarchy
5sealed class AuthState {}
6class AuthInitial extends AuthState {}
7class AuthLoading extends AuthState {}
8class AuthSuccess extends AuthState {
9 final String userName;
10 AuthSuccess(this.userName);
11}
12class AuthFailure extends AuthState {
13 final String message;
14 AuthFailure(this.message);
15}
16
17// Clean, exhaustive Flutter UI builder:
18Widget buildAuthScreen(AuthState state) => switch (state) {
19 AuthInitial() => const Center(child: Text('Please log in')),
20 AuthLoading() => const Center(child: CircularProgressIndicator()),
21 AuthSuccess(:final userName) => Center(child: Text('Welcome, \$userName!')),
22 AuthFailure(:final message) => Center(child: Text('Error: \$message', style: const TextStyle(color: Colors.red))),
23 // Notice: NO default (_) case! If a new state is added, the compiler alerts us immediately!
24};

Avoid Wildcard in Sealed Switches

⚠️ Avoid Wildcard in Sealed Switches

Avoid adding a default case (_ =>) when switching over a sealed class. Doing so defeats the compiler exhaustiveness check! When you add a new state subclass later, the compiler will not warn you if a wildcard catches it.

Dart 3 Best Practices Checklist

  • Use Records whenever returning 2 to 4 temporary paired values from methods.
  • Use Pattern Destructuring to unpack data cleanly in one line.
  • Prefer switch expressions over verbose switch statements and if-else chains.
  • Model UI states and business states as sealed class hierarchies for compile-time safety.
  • Use guard clauses (when) for nuanced boundary conditions.

This Lesson In Simple Words

Master modern Dart 3 language features: records, pattern matching, destructuring, and exhaustive sealed classes. 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 is a Record in Dart 3?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • const: A compile-time constant that can reduce rebuild work.
  • null safety: Dart type system feature that prevents null reference errors.

Lesson Completion Checklist

  • I can explain "Dart 3: Records, Patterns & Sealed Classes" 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 is a Record in Dart 3?

Records allow functions to bundle and return multiple typed values without having to create boilerplate class definitions.

How does a switch expression differ from a traditional switch statement in Dart 3?

Switch expressions evaluate to a value and return it directly. They use => syntax and do not require break statements.

What is the main advantage of using a sealed class for UI state management?

Because all subclasses of a sealed class must reside in the same file, Dart guarantees compile-time exhaustiveness in switch expressions, preventing unhandled states.

What does pattern destructuring do when receiving a record (final (x, y) = getPoint();)?

Pattern destructuring unpacks the individual values of a record directly into individual named variables in a single expressive line.

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