Dive into Dart's patterns and records

1. Introduction

Dart 3 introduces patterns to the language, a major category of grammar. Beyond this way to write Dart code, Dart 3 includes several other language enhancements:

  • Records for bundling data of different types.
  • Class modifiers (such as sealed) for controlling access and enabling exhaustiveness checking.
  • Enhanced switch expressions, if-case statements, and guard clauses.

These features expand the choices you have when writing Dart code. In this codelab, you collaborate with Google Antigravity to learn how to use them to make your code more compact, streamlined, and flexible.

What you'll build

In this codelab, you'll collaborate with Google Antigravity to build an application that displays a structured JSON document in Flutter. The application simulates JSON coming from an external source containing document metadata (title and modification date) and content blocks (headers, paragraphs, and to-do checkboxes).

You'll prompt Antigravity to pack data into records so that it can be transferred and unpacked wherever your Flutter widgets need it, use patterns to validate and destructure JSON data into local variables, and pair switch expressions with sealed classes to build the appropriate widget for each content block.

The final application you build in this codelab, showing a document with a title, relative modification date, headers, paragraphs, and a checkbox

Your learning journey

This codelab takes you through building the document viewer step by step:

  1. Set up your Flutter environment - Configure the Flutter SDK and Google Antigravity for your target platform.
  2. Create a project - Prompt Antigravity to scaffold patterns_codelab with mock JSON data in lib/data.dart and a starter DocumentScreen in lib/main.dart.
  3. Create and return records - Return multiple values of different types from a getter using a record and read its positional and named fields.
  4. Match and destructure with patterns - Unpack record fields directly into local variables using a pattern variable declaration and field shorthand.
  5. Use patterns to extract data - Validate and extract nested JSON values safely using refutable if-case map patterns.
  6. Prepare the app for more patterns - Parse a JSON array into Block instances using map patterns and a collection-for list literal.
  7. Use patterns to display the document - Render Block items in the UI using enhanced switch statements with logical-or and wildcard patterns.
  8. Use switch expressions - Convert the switch statement into a concise switch expression that returns a value directly.
  9. Use object patterns - Match against Duration properties and apply when guard clauses to format human-readable relative dates.
  10. Seal a class for exhaustive switching - Refactor Block into a sealed class hierarchy so the Dart analyzer enforces exhaustive switching across every block subtype.

What you'll learn

  • How to collaborate with Google Antigravity to iteratively build and customize a Flutter document viewer using Dart 3 language features.
  • How to create a record that stores and returns multiple values with different types.
  • How to use patterns to match, validate, and destructure data from records, maps, and objects.
  • How to bind pattern-matched values to new local variables.
  • How to use enhanced switch statement capabilities, switch expressions, guard clauses (when), and if-case statements.
  • How to take advantage of exhaustiveness checking with sealed classes to ensure that every case is handled in a switch statement or switch expression.

Prerequisites

This codelab assumes you have some familiarity with Flutter and Dart. If you feel a little rusty, consider brushing up on the basics with the following resources:

2. Set up your Flutter environment

Editor

This codelab uses Google Antigravity as your AI-first development environment. In each step, you prompt Antigravity to generate or evolve your app's components, review the key Dart 3 patterns and records concepts in the generated code, and optionally explore variations.

Install Flutter

The most up-to-date instructions on installing the Flutter SDK are always on docs.flutter.dev.

For this codelab, install the following software:

  1. Flutter SDK
  2. Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
  3. Compiler software for your chosen development target (for example, Visual Studio to target Windows, Xcode to target macOS or iOS, or Chrome to target the web).

To verify that your environment is set up for your chosen deployment target, run flutter doctor:

flutter doctor

3. Create a project

Before diving into patterns, records, and other Dart 3 features, prompt Antigravity to create a Flutter project with two Dart files that you'll evolve throughout this codelab:

  • lib/data.dart, which holds the mock JSON document and Document data class.
  • lib/main.dart, which contains the Flutter widgets that render the document.

Prompt Antigravity to create the project

  1. Launch Google Antigravity and open an empty directory where you'd like to build your project (choose a path that doesn't require elevated privileges or contain spaces, such as a folder in your home directory or C:\src\).
  2. In the Antigravity agent chat panel, send the following prompt to create the Flutter project and set up lib/data.dart and lib/main.dart:
Create a new empty Flutter project named `patterns_codelab` with a minimum Dart SDK constraint of `^3.0.0`, and add the `material_ui` package. Create `lib/data.dart` with a `Document` class that decodes a multi-line `documentJson` constant (containing a `"metadata"` object with `"title": "My Document"` and `"modified": "2023-05-10"`, and a `"blocks"` list with an `"h1"` header `"Section 1"`, a `"p"` paragraph `"Lorem ipsum dolor sit amet, consectetur adipiscing elit."`, and an unchecked `"checkbox"` `"Learn Dart 3"`) into a `final Map<String, Object?> _json` field. Then update `lib/main.dart` (importing `package:material_ui/material_ui.dart`) to run a `DocumentApp` widget whose home is `DocumentScreen(document: Document())`, rendering a `Scaffold` with placeholder `'Title goes here'` and `'Body goes here'` text.

Understanding the generated code

Minimum SDK version in pubspec.yaml

Passing the --empty flag to flutter create scaffolds a minimal Flutter project without the default counter app boilerplate. In pubspec.yaml, the SDK version constraint specifies Dart 3 or higher using caret syntax:

environment:
  sdk: ^3.0.0

Mocking incoming JSON in lib/data.dart

Imagine a program receiving data from an external source, such as an I/O stream or an HTTP request. In lib/data.dart, documentJson mocks that incoming JSON payload with a multi-line string, and the Document constructor parses it into _json using jsonDecode:

import 'dart:convert';

class Document {
  final Map<String, Object?> _json;
  Document() : _json = jsonDecode(documentJson);
}

Scaffolding DocumentApp and DocumentScreen in lib/main.dart

In lib/main.dart, Antigravity defines two stateless widgets:

  • DocumentApp sets up Material Design (package:material_ui/material_ui.dart) for theming the UI.
  • DocumentScreen provides the visual layout of the page using the Scaffold widget:
class DocumentScreen extends StatelessWidget {
  final Document document;

  const DocumentScreen({required this.document, super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Title goes here')),
      body: const Column(children: [Center(child: Text('Body goes here'))]),
    );
  }
}

Run and test the app

Run the app on your chosen target platform (such as Chrome, macOS, Windows, Linux, iOS, or Android). You should see an app frame displaying the placeholder title and body text defined in DocumentScreen:

The starter application displaying Title goes here in the app bar and Body goes here in the body

4. Create and return records

In this step, you use a record to return multiple values from a single getter call, and then access the record's fields in DocumentScreen to display them in the UI.

Prompt Antigravity to return and read a record

Send the following prompt in Antigravity:

In `lib/data.dart`, add a `metadata` getter to `Document` with return type `(String, {DateTime modified})` that returns a hardcoded record `('My Document', modified: DateTime.now())`. In `lib/main.dart`, call `document.metadata` inside `DocumentScreen.build`, display the positional title field (`metadataRecord.$1`) in the `AppBar`, and display `'Last modified ${metadataRecord.modified}'` in the body.

Understanding the generated code

Returning a record from Document.metadata

In lib/data.dart, the metadata getter returns a record with two fields—one with type String, and the other with type DateTime:

  (String, {DateTime modified}) get metadata {
    const title = 'My Document';
    final now = DateTime.now();

    return (title, modified: now);
  }

The return statement constructs a new record by enclosing the two values in parentheses: (title, modified: now). The first field is positional and unnamed, and the second field is named modified.

Accessing positional and named record fields

In lib/main.dart, DocumentScreen.build assigns document.metadata to metadataRecord and reads its fields using built-in record getters:

  @override
  Widget build(BuildContext context) {
    final metadataRecord = document.metadata;

    return Scaffold(
      appBar: AppBar(title: Text(metadataRecord.$1)),
      body: Column(
        children: [
          Center(child: Text('Last modified ${metadataRecord.modified}')),
        ],
      ),
    );
  }
  • To get a positional field (a field without a name, like title), use the getter $ on the record (starting at $1 and skipping named fields).
  • Named fields like modified don't have a positional getter; you access them directly by their field name, such as metadataRecord.modified.

For example, in a record that mixes named and positional fields, positional getters number only the unnamed fields:

var record = (named: 'v', 'y', named2: 'x', 'z');
print(record.$1); // prints y
print(record.$2); // prints z

Each field in the record maintains its static type: Text() receives metadataRecord.$1 as a String, while metadataRecord.modified is a DateTime that converts to a String using string interpolation.

Run and test the app

Hot reload the app to see the title and current timestamp displayed on screen:

The app displaying My Document in the app bar and the Last modified timestamp in the body

5. Match and destructure with patterns

Records can efficiently collect different types of data and pass them around. Now, you'll improve the code in DocumentScreen using patterns.

A pattern represents a structure that one or more values can take, like a blueprint. Patterns compare against actual values to determine if they match. When a pattern matches, it can destructure the matched value by pulling data out of it and binding those values to local variables.

Prompt Antigravity to destructure the record

Send the following prompt in Antigravity:

Refactor `DocumentScreen.build` in `lib/main.dart` to destructure `document.metadata` directly into local `title` and `modified` variables using the record pattern shorthand `final (title, :modified) = document.metadata;`, and use `title` and `modified` in the `AppBar` and body `Text` widgets.

Understanding the generated code

Destructuring a record into local variables

Instead of storing the record in a temporary variable and reading $1 and .modified, you can initialize a pattern variable declaration:

  @override
  Widget build(BuildContext context) {
    final (title, :modified) = document.metadata;

    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Column(children: [Center(child: Text('Last modified $modified'))]),
    );
  }

The record pattern (title, :modified) (which is shorthand for (title, modified: modified)) contains two variable patterns that match against the fields of the record returned by metadata:

  • The expression matches the pattern because the result is a record with two fields, one positional and one named modified.
  • Because they match, the variable declaration pattern destructures the expression, accessing its values and binding them to new local variables of the same types and names: String title and DateTime modified.
  • When the name of a named field and the variable populating it are the same, :modified is shorthand for modified: modified. If you want a local variable with a different name, you can write modified: localModified instead.

Run and test the app

Hot reload the app to verify that the result is identical to the previous step, now written with more concise and readable code.

6. Use patterns to extract data

In certain contexts, patterns don't only match and destructure—they can also make a decision about what the code does based on whether or not the pattern matches. These are called refutable patterns.

The variable declaration pattern you used in the previous step is an irrefutable pattern: the value must match the pattern or it's a compile-time error, and destructuring won't happen (just like you can't assign a value to a variable of a different type).

Refutable patterns, on the other hand, are used in control flow contexts:

  • They expect that some values they compare against won't match.
  • They are meant to influence the control flow, based on whether or not the value matches.
  • They don't interrupt execution with an error if they don't match; they just move to the next statement or branch.
  • They can destructure and bind variables that are only usable in the branch where they match.

Prompt Antigravity to parse metadata with a map pattern

Send the following prompt in Antigravity:

Update the `metadata` getter in `lib/data.dart` to read and validate the JSON structure using an `if-case` map pattern (`if (_json case {'metadata': {'title': String title, 'modified': String localModified}})`) that returns `(title, modified: DateTime.parse(localModified))` and throws a `FormatException('Unexpected JSON')` otherwise.

Understanding the generated code

Comparing manual JSON validation versus map patterns

Without pattern matching, reading and validating nested values from _json requires multiple nested checks and explicit type casts:

  (String, {DateTime modified}) get metadata {
    if (_json.containsKey('metadata')) {
      final metadataJson = _json['metadata'];
      if (metadataJson is Map) {
        final title = metadataJson['title'] as String;
        final localModified = DateTime.parse(
          metadataJson['modified'] as String,
        );
        return (title, modified: localModified);
      }
    }
    throw const FormatException('Unexpected JSON');
  }

With a refutable map pattern inside an if-case statement (introduced in Dart 3), you can verify that the JSON has the expected structure and extract the values in a single step:

  (String, {DateTime modified}) get metadata {
    if (_json case {
      'metadata': {'title': String title, 'modified': String localModified},
    }) {
      return (title, modified: DateTime.parse(localModified));
    } else {
      throw const FormatException('Unexpected JSON');
    }
  }

The case body only executes if the map pattern matches the data in _json. This single pattern validates that:

  • _json is a Map type and isn't null.
  • _json contains a 'metadata' key.
  • _json['metadata'] is also a non-null Map type.
  • _json['metadata'] contains the keys 'title' and 'modified'.
  • title and localModified are non-null String values.

If the value doesn't match any of those conditions, the pattern refutes the match and execution proceeds to the else clause. If the match succeeds, the pattern destructures the title and modified strings from the map and binds them to new local variables.

For a full list of patterns, see the Patterns documentation on dart.dev.

Run and test the app

Hot reload the app. The Last modified timestamp now reflects "2023-05-10" from documentJson rather than DateTime.now(), and the unused_field warning on _json is gone.

7. Prepare the app for more patterns

So far, you've handled the metadata portion of the JSON data. In this step, you'll add a Block class and a getBlocks() method in lib/data.dart to parse the blocks list from documentJson so it can be rendered in your UI.

Prompt Antigravity to parse the blocks list

Send the following prompt in Antigravity:

In `lib/data.dart`, add a `Block` class with `final String type` and `final String text` fields and a `factory Block.fromJson(Map<String, dynamic> json)` constructor that uses an `if-case` map pattern (`{'type': final type, 'text': final text}`) to return a `Block` or throw a `FormatException('Unexpected JSON format')`. Then add a `List<Block> getBlocks()` method to `Document` that matches `_json` against `{'blocks': List blocksJson}` and returns `[for (final blockJson in blocksJson) Block.fromJson(blockJson)]` (or throws a `FormatException('Unexpected JSON format')`).

Understanding the generated code

Ignoring extra keys in map patterns (Block.fromJson)

In lib/data.dart, the Block.fromJson() factory constructor uses an if-case statement with a map pattern to extract 'type' and 'text':

class Block {
  final String type;
  final String text;
  Block(this.type, this.text);

  factory Block.fromJson(Map<String, dynamic> json) {
    if (json case {'type': final type, 'text': final text}) {
      return Block(type, text);
    } else {
      throw const FormatException('Unexpected JSON format');
    }
  }
}

Notice that the third block in documentJson ("type": "checkbox") also includes a "checked": false key that isn't mentioned in the pattern. Map patterns still match even when the map contains extra keys not listed in the pattern—they validate and extract the keys you specify and ignore any additional entries in the map.

Extracting the list in Document.getBlocks

In Document, the getBlocks() method validates that _json contains a 'blocks' list and constructs a List:

  List<Block> getBlocks() {
    if (_json case {'blocks': List blocksJson}) {
      return [for (final blockJson in blocksJson) Block.fromJson(blockJson)];
    } else {
      throw const FormatException('Unexpected JSON format');
    }
  }

The if-case statement validates that _json['blocks'] is a List and binds it to blocksJson (without patterns, you'd need an explicit cast or toList()). Inside the list literal, a collection for iterates over blocksJson to build the list of Block objects.

Run and test the app

Hot reload the app to confirm there are no analyzer or runtime errors. In the next step, you'll render the parsed Block items on screen.

8. Use patterns to display the document

You've used if-case statements and refutable patterns to destructure and recompose your JSON data. Now you'll apply refutable patterns to switch statements to style and render each Block in lib/main.dart.

Prompt Antigravity to render the document blocks

Send the following prompt in Antigravity:

In `lib/main.dart`, create a `BlockWidget` `StatelessWidget` that takes a `required Block block` and uses a `switch` statement on `block.type` to assign `textStyle` (`displayMedium` for `'h1'`, `bodyMedium` for `'p' || 'checkbox'`, and `bodySmall` for the wildcard `_`), rendering `Text(block.text, style: textStyle)` inside an 8px-margin `Container`. Then update `DocumentScreen.build` to call `document.getBlocks()` and display `'Last modified: $modified'` above an `Expanded` `ListView.builder` that renders a `BlockWidget` for each block.

Understanding the generated code

Pattern matching in switch statements

In lib/main.dart, BlockWidget.build switches on block.type using three pattern features:

class BlockWidget extends StatelessWidget {
  final Block block;

  const BlockWidget({required this.block, super.key});

  @override
  Widget build(BuildContext context) {
    TextStyle? textStyle;
    switch (block.type) {
      case 'h1':
        textStyle = Theme.of(context).textTheme.displayMedium;
      case 'p' || 'checkbox':
        textStyle = Theme.of(context).textTheme.bodyMedium;
      case _:
        textStyle = Theme.of(context).textTheme.bodySmall;
    }

    return Container(
      margin: const EdgeInsets.all(8),
      child: Text(block.text, style: textStyle),
    );
  }
}
  1. Constant string pattern (case 'h1':): Matches if block.type is equal to the constant 'h1'.
  2. Logical-or pattern (case 'p' || 'checkbox':): Matches if block.type matches either of the subpatterns 'p' or 'checkbox'. (Logical-and patterns using && are also supported.)
  3. Wildcard pattern (case _:): Matches any value without binding a variable. In a switch statement, case _: behaves like a default: clause (which is still allowed, just slightly more verbose), and can also be used in any pattern context—such as var (title, _) = document.metadata; to discard the second record field.

Displaying the block list in DocumentScreen

In DocumentScreen.build, calling document.getBlocks() populates an Expanded ListView.builder that constructs a BlockWidget for each item:

    final (title, :modified) = document.metadata;
    final blocks = document.getBlocks();

    return Scaffold(
      appBar: AppBar(title: Text(title)),
      body: Column(
        children: [
          Text('Last modified: $modified'),
          Expanded(
            child: ListView.builder(
              itemCount: blocks.length,
              itemBuilder: (context, index) {
                return BlockWidget(block: blocks[index]);
              },
            ),
          ),
        ],
      ),
    );

Run and test the app

Hot reload the application to see the blocks from documentJson rendered on screen:

The app displaying the document heading, paragraph text, and Learn Dart 3 text from the blocks section of the JSON data

9. Use switch expressions

Patterns add expressive capabilities to switch and case. To make them usable in more places—such as variable initializers, return statements, and widget trees—Dart 3 introduces switch expressions, which evaluate a series of pattern cases and produce a value directly.

Prompt Antigravity to convert to a switch expression

Send the following prompt in Antigravity:

Refactor `BlockWidget.build` in `lib/main.dart` to replace the `switch` statement on `block.type` with a `switch` expression that assigns `textStyle` directly.

Understanding the generated code

switch expression syntax

In lib/main.dart, BlockWidget.build now assigns textStyle directly from a switch expression:

  @override
  Widget build(BuildContext context) {
    final textStyle = switch (block.type) {
      'h1' => Theme.of(context).textTheme.displayMedium,
      'p' || 'checkbox' => Theme.of(context).textTheme.bodyMedium,
      _ => Theme.of(context).textTheme.bodySmall,
    };

    return Container(
      margin: const EdgeInsets.all(8),
      child: Text(block.text, style: textStyle),
    );
  }

A switch expression looks similar to a switch statement, with three syntax differences:

  • It omits the case keyword before each pattern.
  • It uses => instead of : to separate each pattern from its expression body.
  • It separates cases with commas (,) and can be used anywhere an expression is expected.

Run and test the app

Hot reload the app to verify that the document blocks continue to render with their expected text styles.

10. Use object patterns

Dart is an object-oriented language, and patterns apply to all Dart objects. In this step, you'll match against object patterns and destructure object getters—combined with when guard clauses—to display a human-readable relative modification date (such as "today", "yesterday", or "2 weeks ago").

Prompt Antigravity to format relative dates with object patterns

Send the following prompt in Antigravity:

Add a `String formatDate(DateTime dateTime)` function in `lib/main.dart` that computes `final difference = dateTime.difference(DateTime.now())` and returns a `switch` expression matching `Duration` object patterns: `'today'` for `0` days, `'tomorrow'` for `1` day, `'yesterday'` for `-1` days, `'${days ~/ 7} weeks from now'` when `days > 7`, `'${days.abs() ~/ 7} weeks ago'` when `days < -7`, `'${days.abs()} days ago'` when `isNegative: true`, and `'$days days from now'` for any remaining `Duration(inDays: final days)`. Update `DocumentScreen.build` to format `modified` with `formatDate(modified)` and display `'Last modified: $formattedModifiedDate'`.

Understanding the generated code

Destructuring getters with Duration object patterns

In lib/main.dart, formatDate calculates the Duration between dateTime and DateTime.now() and switches on difference:

String formatDate(DateTime dateTime) {
  final today = DateTime.now();
  final difference = dateTime.difference(today);

  return switch (difference) {
    Duration(inDays: 0) => 'today',
    Duration(inDays: 1) => 'tomorrow',
    Duration(inDays: -1) => 'yesterday',
    Duration(inDays: final days) when days > 7 => '${days ~/ 7} weeks from now',
    Duration(inDays: final days) when days < -7 =>
      '${days.abs() ~/ 7} weeks ago',
    Duration(inDays: final days, isNegative: true) => '${days.abs()} days ago',
    Duration(inDays: final days) => '$days days from now',
  };
}

Although Duration(inDays: ...) looks like a constructor call, in a pattern context it is an object pattern that verifies the value is a Duration and calls the inDays and isNegative getters on difference:

  • The first three cases use constant subpatterns (0, 1, and -1) to match difference.inDays and return 'today', 'tomorrow', or 'yesterday'.
  • The last two cases handle durations beyond a single day by binding inDays to final days: if isNegative matches the boolean constant true, the date is in the past ('${days.abs()} days ago'); otherwise, the remaining case catches positive durations ('$days days from now').

Filtering matches with when guard clauses

To format spans longer than 7 days as weeks, the middle two cases add guard clauses:

    Duration(inDays: final days) when days > 7 => '${days ~/ 7} weeks from now',
    Duration(inDays: final days) when days < -7 =>
      '${days.abs() ~/ 7} weeks ago',
  • A guard clause uses the when keyword after a case pattern and can be used in if-case statements, switch statements, and switch expressions.
  • It evaluates an arbitrary boolean condition after the pattern matches and binds its variables (days).
  • If the guard expression evaluates to false, the pattern is refuted and execution moves on to the next case instead of exiting the switch.

Run and test the app

Hot reload the app to see the formatted relative modification date in DocumentScreen (try changing "modified" in documentJson to a date two weeks ago to see "Last modified: 2 weeks ago"):

The app displaying a relative modification date using the formatDate function

11. Seal a class for exhaustive switching

Notice that formatDate in the previous step didn't need a wildcard (_) case at the end because Duration(inDays: final days) accounts for every possible Duration value. When every possible value in a switch is handled, it's called an exhaustive switch.

In Dart 3, the sealed class modifier extends exhaustiveness checking to class hierarchies. In this final step, you'll refactor Block into a sealed superclass with three subclasses (HeaderBlock, ParagraphBlock, and CheckboxBlock) and use an exhaustive switch expression in BlockWidget to render each block type—including an interactive Checkbox row for CheckboxBlock.

Prompt Antigravity to seal Block and render all block subtypes

Send the following prompt in Antigravity:

In `lib/data.dart`, refactor `Block` into a `sealed class Block` with three subclasses (`HeaderBlock(this.text)`, `ParagraphBlock(this.text)`, and `CheckboxBlock(this.text, this.isChecked)`) and replace `Block.fromJson` (`Map<String, Object?> json`) with a `switch` expression matching map patterns for `'h1'`, `'p'`, and `'checkbox'`. Then update `BlockWidget.build` in `lib/main.dart` to use an exhaustive `switch (block)` expression directly as the `Container`'s `child`, destructuring `HeaderBlock(:final text)`, `ParagraphBlock(:final text)`, and `CheckboxBlock(:final text, :final isChecked)` (rendering a `Row` with a `Checkbox` and `Text` for `CheckboxBlock`).

Understanding the generated code

Modeling a sealed class hierarchy in lib/data.dart

In lib/data.dart, Block is marked with the sealed class modifier and extended by HeaderBlock, ParagraphBlock, and CheckboxBlock:

sealed class Block {
  Block();

  factory Block.fromJson(Map<String, Object?> json) {
    return switch (json) {
      {'type': 'h1', 'text': String text} => HeaderBlock(text),
      {'type': 'p', 'text': String text} => ParagraphBlock(text),
      {'type': 'checkbox', 'text': String text, 'checked': bool checked} =>
        CheckboxBlock(text, checked),
      _ => throw const FormatException('Unexpected JSON format'),
    };
  }
}

class HeaderBlock extends Block {
  final String text;
  HeaderBlock(this.text);
}

class ParagraphBlock extends Block {
  final String text;
  ParagraphBlock(this.text);
}

class CheckboxBlock extends Block {
  final String text;
  final bool isChecked;
  CheckboxBlock(this.text, this.isChecked);
}

The sealed keyword means Block can only be extended or implemented in the same library (lib/data.dart). Because the Dart analyzer knows the complete, closed set of direct subtypes for Block, it can verify whether any switch over a Block instance handles every subtype.

Exhaustive object-pattern switching in BlockWidget

In lib/main.dart, BlockWidget.build passes a switch (block) expression directly to the Container's child property, matching against each subclass with an object pattern and destructuring its fields using :final shorthand:

class BlockWidget extends StatelessWidget {
  final Block block;

  const BlockWidget({required this.block, super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(8),
      child: switch (block) {
        HeaderBlock(:final text) => Text(
          text,
          style: Theme.of(context).textTheme.displayMedium,
        ),
        ParagraphBlock(:final text) => Text(text),
        CheckboxBlock(:final text, :final isChecked) => Row(
          children: [
            Checkbox(value: isChecked, onChanged: (_) {}),
            Text(text),
          ],
        ),
      },
    );
  }
}

Run and test the app

Hot reload the app to see the checkbox block rendered with a Material Checkbox widget for the first time:

The app displaying the document heading, paragraph text, and an unchecked Learn Dart 3 checkbox

12. Congratulations

Congratulations! You collaborated with Google Antigravity to build a Flutter document viewer powered by Dart 3 records, patterns, enhanced switch expressions, and sealed classes.

What you've built

  • Multi-value returns with records: Returned positional and named fields ((String, {DateTime modified})) from Document.metadata and destructured them cleanly into local variables with final (title, :modified) = document.metadata;.
  • Safe JSON validation and extraction: Used refutable if-case statements and switch expressions with nested map patterns to validate types, check for keys, and extract values in a single expression.
  • Expressive UI branching: Used switch expressions, object patterns (Duration(inDays: final days)), and when guard clauses to format relative timestamps and build widgets inline.
  • Compile-time exhaustiveness checking: Modeled document content blocks as a sealed class Block hierarchy (HeaderBlock, ParagraphBlock, and CheckboxBlock) so the compiler ensures every block type is rendered.

What's next?

Check out the official Dart documentation to explore more pattern types, record features, and class modifiers:

Reference docs

For in-depth language specifications for each feature covered in this codelab, check out the original Dart language design documents: