1. 簡介
Dart 3 導入了模式,這是語法的一大類別。除了這種編寫 Dart 程式碼的方式外,Dart 3 還包含其他幾項語言強化功能:
- 記錄:用於彙整不同類型的資料。
- 類別修飾符 (例如
sealed),用於控管存取權及啟用完整性檢查。 - 強化切換運算式、if-case 陳述式和防護子句。
這些功能可讓您在編寫 Dart 程式碼時有更多選擇。在本程式碼實驗室中,您將與 Google Antigravity 合作,瞭解如何使用這些工具,讓程式碼更精簡、流暢且靈活。
建構項目
在本程式碼實驗室中,您將與 Google Antigravity 合作,建構一個在 Flutter 中顯示結構化 JSON 文件的應用程式。應用程式會模擬來自外部來源的 JSON,其中包含文件詮釋資料 (標題和修改日期) 和內容區塊 (標題、段落和待辦事項核取方塊)。
您將提示 Antigravity 將資料封裝成記錄,以便在 Flutter 小工具需要時傳輸及解壓縮,並使用模式驗證 JSON 資料並解構為本機變數,以及將 switch 運算式與 sealed 類別配對,為每個內容區塊建構適當的小工具。

學習旅程
本程式碼實驗室會逐步引導您建構文件檢視器:
- 設定 Flutter 環境:為目標平台設定 Flutter SDK 和 Google Antigravity。
- 建立專案:提示 Antigravity 在
patterns_codelab中建立lib/data.dart模擬 JSON 資料和lib/main.dart範例DocumentScreen的鷹架。 - 建立並傳回記錄:使用記錄從 getter 傳回多個不同類型的值,並讀取其位置和具名欄位。
- 使用模式比對和解構:使用模式變數宣告和欄位簡寫,直接將記錄欄位解構為區域變數。
- 使用模式擷取資料:使用可駁斥的
if-case對應模式,安全地驗證及擷取巢狀 JSON 值。 - 為應用程式準備更多模式:使用對應模式和集合 for 清單常值,將 JSON 陣列剖析為
Block執行個體。 - 使用模式顯示文件:使用增強型
switch陳述式,搭配邏輯或和萬用字元模式,在 UI 中算繪Block項目。 - 使用 switch 運算式:將
switch陳述式轉換為簡潔的switch運算式,直接傳回值。 - 使用物件模式:比對
Duration屬性,並套用when防護子句,設定人類可讀的相對日期格式。 - 密封類別以進行完整切換:將
Block重構為sealed類別階層,讓 Dart 分析器強制對每個區塊子類型進行完整切換。
課程內容
- 如何與 Google Antigravity 協作,使用 Dart 3 語言功能,反覆建構及自訂 Flutter 文件檢視器。
- 如何建立記錄,儲存及傳回多個不同類型的值。
- 如何使用模式比對、驗證及解構記錄、對應和物件中的資料。
- 如何將模式比對值繫結至新的區域變數。
- 如何使用強化版
switch陳述式功能、switch運算式、防護子句 (when) 和if-case陳述式。 - 如何利用
sealed類別的完整性檢查,確保switch陳述式或switch運算式會處理每個案例。
必要條件
本程式碼實驗室假設您對 Flutter 和 Dart 有一定程度的瞭解。如果覺得有點生疏,建議您利用下列資源溫習基本知識:
2. 設定 Flutter 環境
編輯者
本程式碼實驗室會使用 Google Antigravity 做為 AI 優先開發環境。在每個步驟中,您會提示 Antigravity 生成或演進應用程式的元件、查看生成程式碼中的重要 Dart 3 模式和記錄概念,並視需要探索變化版本。
安裝 Flutter
如需安裝 Flutter SDK 的最新操作說明,請前往 docs.flutter.dev。
請安裝下列軟體,以便進行本程式碼實驗室:
- Flutter SDK
- Google Antigravity,並啟用官方 Dart 和 Flutter 外掛程式 (可在外掛程式市集的「Build with Google」部分找到)。
- 所選開發目標的編譯器軟體 (例如 Windows 的 Visual Studio、macOS 或 iOS 的 Xcode,或網頁的 Chrome)。
如要確認環境已針對所選部署目標設定完成,請執行 flutter doctor:
flutter doctor
3. 建立專案
在深入瞭解模式、記錄和其他 Dart 3 功能之前,請提示 Antigravity 建立 Flutter 專案,其中包含兩個 Dart 檔案,您將在本程式碼實驗室中逐步開發這些檔案:
lib/data.dart,其中包含模擬 JSON 文件和Document資料類別。lib/main.dart:包含用於轉譯文件的 Flutter 小工具。
提示 Antigravity 建立專案
- 啟動 Google Antigravity,然後開啟要建構專案的空白目錄 (請選擇不需進階權限或不含空格的路徑,例如主目錄或
C:\src\中的資料夾)。 - 在 Antigravity 代理程式對話面板中,傳送下列提示詞,建立 Flutter 專案並設定
lib/data.dart和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.
瞭解生成的程式碼
pubspec.yaml 中的 SDK 最低版本
將 --empty 旗標傳遞至 flutter create,即可建構最小的 Flutter 專案,不含預設計數器應用程式樣板。在 pubspec.yaml 中,SDK 版本限制會使用插入點語法指定 Dart 3 以上版本:
environment:
sdk: ^3.0.0
在 lib/data.dart 中模擬傳入的 JSON
假設某個程式從外部來源 (例如輸入輸出流或 HTTP 要求) 接收資料。在 lib/data.dart 中,documentJson 會使用多行字串模擬傳入的 JSON 酬載,而 Document 建構函式會使用 jsonDecode 將其剖析為 _json:
import 'dart:convert';
class Document {
final Map<String, Object?> _json;
Document() : _json = jsonDecode(documentJson);
}
在 lib/main.dart 中建構 DocumentApp 和 DocumentScreen
在 lib/main.dart 中,Antigravity 定義了兩個無狀態小工具:
DocumentApp會設定 Material Design (package:material_ui/material_ui.dart) 來設定 UI 主題。DocumentScreen使用Scaffold小工具提供頁面的視覺版面配置:
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'))]),
);
}
}
執行及測試應用程式
在所選目標平台 (例如 Chrome、macOS、Windows、Linux、iOS 或 Android) 上執行應用程式。您應該會看到應用程式框架,其中顯示 DocumentScreen 中定義的預留位置 title 和 body 文字:

4. 建立及傳回記錄
在這個步驟中,您將使用記錄從單一 getter 呼叫傳回多個值,然後存取 DocumentScreen 中的記錄欄位,以便在 UI 中顯示這些欄位。
提示 Antigravity 傳回並讀取記錄
在 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.
瞭解生成的程式碼
從 Document.metadata 傳回記錄
lib/data.dart 中的 metadata getter 會傳回包含兩個欄位的記錄,一個是 String 類型,另一個是 DateTime 類型:
(String, {DateTime modified}) get metadata {
const title = 'My Document';
final now = DateTime.now();
return (title, modified: now);
}
回傳敘述會將兩個值括在括號中,藉此建構新記錄:(title, modified: now)。第一個欄位是位置欄位,沒有名稱,第二個欄位則名為 modified。
存取位置和具名記錄欄位
在 lib/main.dart 中,DocumentScreen.build 會將 document.metadata 指派給 metadataRecord,並使用內建記錄 getter 讀取其欄位:
@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}')),
],
),
);
}
- 如要取得位置欄位 (沒有名稱的欄位,例如
title),請在記錄上使用 getter$(從$1開始,並略過已命名的欄位)。 modified等具名欄位沒有位置 getter,您可直接透過欄位名稱 (例如metadataRecord.modified) 存取。
舉例來說,在混合具名和位置欄位的記錄中,位置 getter 只會為未命名的欄位編號:
var record = (named: 'v', 'y', named2: 'x', 'z');
print(record.$1); // prints y
print(record.$2); // prints z
記錄中的每個欄位都會維持其靜態類型:Text() 接收 metadataRecord.$1 做為 String,而 metadataRecord.modified 是 DateTime,會使用字串內插轉換為 String。
執行及測試應用程式
熱重載應用程式,畫面上就會顯示標題和目前的時間戳記:

5. 使用模式進行比對和解構
記錄可有效收集不同類型的資料並傳遞。現在,您將使用模式改善 DocumentScreen 中的程式碼。
模式代表一或多個值可以採用的結構,就像藍圖一樣。系統會將模式與實際值進行比較,判斷兩者是否相符。當模式相符時,可以從相符的值中提取資料,並將這些值繫結至區域變數,藉此解構相符的值。
提示 Antigravity 解構記錄
在 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.
瞭解生成的程式碼
將記錄解構為本機變數
您可以初始化模式變數宣告,而不是將記錄儲存在暫時變數中,並讀取 $1 和 .modified:
@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'))]),
);
}
記錄模式 (title, :modified) ((title, modified: modified) 的簡寫) 包含兩個變數模式,與 metadata 傳回的記錄欄位比對:
- 運算式與模式相符,因為結果是包含兩個欄位的記錄,一個是位置欄位,另一個是名為
modified的欄位。 - 由於兩者相符,變數宣告模式會解構運算式,存取其值並繫結至相同類型和名稱的新區域變數:
String title和DateTime modified。 - 如果已命名欄位的名稱和填入該欄位的變數相同,
:modified就是modified: modified的簡寫。如要使用不同名稱的區域變數,可以改寫modified: localModified。
執行及測試應用程式
熱重載應用程式,確認結果與上一步相同,但現在程式碼更簡潔易讀。
6. 使用模式擷取資料
在某些情況下,模式不只會比對和解構,還能根據模式是否相符,決定程式碼的行為。這稱為「可駁斥模式」。
您在上一步使用的變數宣告模式是「不可駁斥模式」:值必須與模式相符,否則會發生編譯時間錯誤,且不會進行解構 (就像您無法將值指派給不同類型的變數一樣)。
另一方面,可駁斥模式則用於控制流程情境:
- 他們預期部分比較值不會相符。
- 其目的是根據值是否相符,影響控制流程。
- 如果條件不符,不會中斷執行並顯示錯誤,而是直接移至下一個陳述式或分支。
- 它們可以解構和繫結變數,但這些變數只能在相符的分支中使用。
提示 Antigravity 使用地圖模式剖析中繼資料
在 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.
瞭解生成的程式碼
比較手動 JSON 驗證與對應模式
如果不使用模式比對,從 _json 讀取及驗證巢狀值時,需要進行多項巢狀檢查和明確類型轉換:
(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');
}
在 if-case 陳述式 (Dart 3 推出) 中使用可駁斥的地圖模式,即可驗證 JSON 是否具有預期結構,並在單一步驟中擷取值:
(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');
}
}
只有在對應模式與 _json 中的資料相符時,系統才會執行 case 主體。這個單一模式會驗證:
_json是Map類型,且不可為null。_json包含'metadata'鍵。_json['metadata']也是非空值的Map類型。_json['metadata']包含'title'和'modified'鍵。title和localModified是非空值String值。
如果值不符合任何條件,模式會拒絕比對,並繼續執行 else 子句。如果比對成功,模式會從對應中解構 title 和 modified 字串,並繫結至新的區域變數。
如需完整的模式清單,請參閱 dart.dev 上的模式說明文件。
執行及測試應用程式
熱重載應用程式。Last modified 時間戳記現在會反映 documentJson 的 "2023-05-10",而非 DateTime.now(),且 _json 上的 unused_field 警告已消失。
7. 為應用程式做好準備,以便支援更多模式
目前為止,您已處理 JSON 資料的 metadata 部分。在這個步驟中,您要在 lib/data.dart 中新增 Block 類別和 getBlocks() 方法,剖析 documentJson 中的 blocks 清單,以便在 UI 中算繪。
提示 Antigravity 剖析 blocks 清單
在 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')`).
瞭解生成的程式碼
忽略對應模式中的額外鍵 (Block.fromJson)
在 lib/data.dart 中,Block.fromJson() 工廠建構函式使用 if-case 陳述式和對應模式,擷取 'type' 和 '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');
}
}
}
請注意,documentJson ("type": "checkbox") 中的第三個區塊也包含模式中未提及的 "checked": false 鍵。即使對應包含未列在模式中的額外索引鍵,對應模式仍會比對,也就是驗證並擷取您指定的索引鍵,並忽略對應中的任何其他項目。
正在擷取Document.getBlocks中的清單
在 Document 中,getBlocks() 方法會驗證 _json 是否包含 'blocks' 清單,並建構 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');
}
}
if-case 陳述式會驗證 _json['blocks'] 是否為 List,並將其繫結至 blocksJson (如果沒有模式,則需要明確轉換或 toList())。在清單常值中,集合 for 會疊代 blocksJson,以建構 Block 物件清單。
執行及測試應用程式
熱重載應用程式,確認沒有分析器或執行階段錯誤。在下一個步驟中,您將在畫面上算繪剖析後的 Block 項目。
8. 使用模式顯示文件
您已使用 if-case 陳述式和可駁斥模式,解構及重組 JSON 資料。現在,您將對 switch 陳述式套用可駁斥模式,為 lib/main.dart 中的每個 Block 設定樣式及算繪。
提示 Antigravity 算繪文件區塊
在 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.
瞭解生成的程式碼
switch 陳述式中的模式比對
在 lib/main.dart 中,BlockWidget.build 會使用三種模式功能開啟 block.type:
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),
);
}
}
- 常數字串模式 (
case 'h1':):如果block.type等於常數'h1',則相符。 - 邏輯 OR 模式 (
case 'p' || 'checkbox':):如果block.type符合子模式'p'或'checkbox',則視為相符。(也支援使用&&的邏輯 AND 模式)。 - 萬用字元模式 (
case _:):比對任何值,不繫結變數。在switch陳述式中,case _:的行為類似default:子句 (仍允許使用,但稍微冗長),也可以用於任何模式情境,例如var (title, _) = document.metadata;可捨棄第二個記錄欄位。
在DocumentScreen中顯示封鎖清單
在 DocumentScreen.build 中,呼叫 document.getBlocks() 會填入 Expanded ListView.builder,為每個項目建構 BlockWidget:
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]);
},
),
),
],
),
);
執行及測試應用程式
熱重載應用程式,查看畫面上顯示的 documentJson 區塊:

9. 使用 switch 運算式
模式可為 switch 和 case 增添表達能力。為了讓這類陳述式能在更多地方使用 (例如變數初始化器、回傳敘述和 widget 樹狀結構),Dart 3 導入了 switch 運算式,可評估一系列模式案例並直接產生值。
提示 Antigravity 轉換為 switch 運算式
在 Antigravity 中傳送下列提示詞:
Refactor `BlockWidget.build` in `lib/main.dart` to replace the `switch` statement on `block.type` with a `switch` expression that assigns `textStyle` directly.
瞭解生成的程式碼
switch 運算式語法
在 lib/main.dart 中,BlockWidget.build 現在會直接從 switch 運算式指派 textStyle:
@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),
);
}
switch 運算式與 switch 陳述式類似,但有三項語法差異:
- 省略每個模式前的
case關鍵字。 - 它使用
=>而非:來分隔每個模式與其運算式主體。 - 這個函式會以半形逗號 (
,) 分隔案例,並可在任何需要運算式的地方使用。
執行及測試應用程式
熱重載應用程式,確認文件區塊會繼續以預期的文字樣式算繪。
10. 使用物件模式
Dart 是物件導向語言,模式適用於所有 Dart 物件。在這個步驟中,您將比對物件模式,並解構物件 getter (與 when 防護子句結合),以顯示人類可讀的相對修改日期 (例如 "today"、"yesterday" 或 "2 weeks ago")。
提示 Antigravity 使用物件模式設定相對日期的格式
在 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'`.
瞭解生成的程式碼
使用 Duration 物件模式解構 getter
在 lib/main.dart 中,formatDate 會計算 dateTime 和 DateTime.now() 之間的 Duration,並切換 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',
};
}
雖然 Duration(inDays: ...) 看起來像建構函式呼叫,但在模式情境中,它是物件模式,可驗證值是否為 Duration,並在 difference 上呼叫 inDays 和 isNegative getter:
- 前三個案例使用常數子模式 (
0、1和-1) 比對difference.inDays,並傳回'today'、'tomorrow'或'yesterday'。 - 最後兩個案例會將
inDays繫結至final days,藉此處理超過一天的時間長度:如果isNegative符合布林常數true,則日期為過去 ('${days.abs()} days ago');否則,其餘案例會擷取正時間長度 ('$days days from now')。
使用 when 防護子句篩選比對結果
如要將超過 7 天的時間範圍格式化為週,中間兩個 case 會新增防護子句:
Duration(inDays: final days) when days > 7 => '${days ~/ 7} weeks from now',
Duration(inDays: final days) when days < -7 =>
'${days.abs() ~/ 7} weeks ago',
- 防護子句會在 case 模式後方使用
when關鍵字,並可用於if-case陳述式、switch陳述式和switch運算式。 - 在模式比對並繫結變數 (
days) 之後,評估任意布林條件。 - 如果防護運算式的評估結果為
false,模式就會遭到駁回,執行作業會移至下一個 case,而不是退出switch。
執行及測試應用程式
熱重載應用程式,在 DocumentScreen 中查看格式化的相對修改日期 (嘗試將 documentJson 中的 "modified" 變更為兩週前的日期,查看 "Last modified: 2 weeks ago"):

11. 密封類別以進行詳盡切換
請注意,上一個步驟中的 formatDate 不需要結尾的萬用字元 (_) case,因為 Duration(inDays: final days) 會考量每個可能的 Duration 值。當 switch 中的每個可能值都經過處理,就稱為「完整 switch」。
在 Dart 3 中,sealed 類別修飾符會將完整性檢查擴充至類別階層。在最後一個步驟中,您會將 Block 重構為具有三個子類別 (HeaderBlock、ParagraphBlock 和 CheckboxBlock) 的 sealed 父類別,並在 BlockWidget 中使用詳盡的 switch 運算式來算繪每個區塊類型,包括 CheckboxBlock 的互動式 Checkbox 列。
提示 Antigravity 封印Block並顯示所有方塊子類型
在 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`).
瞭解生成的程式碼
在 lib/data.dart 中建立 sealed 類別階層的模型
在 lib/data.dart 中,Block 標有 sealed 類別修飾符,並由 HeaderBlock、ParagraphBlock 和 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);
}
sealed 關鍵字表示 Block 只能在同一個程式庫中擴充或實作 (lib/data.dart)。由於 Dart 分析器知道 Block 的完整封閉式直接子類型組合,因此可以驗證 Block 例項上的任何 switch 是否會處理每個子類型。
BlockWidget 中的詳盡物件模式切換
在 lib/main.dart 中,BlockWidget.build 會將 switch (block) 運算式直接傳遞至 Container 的 child 屬性,並使用物件模式比對每個子類別,然後使用 :final 簡寫解構其欄位:
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),
],
),
},
);
}
}
執行及測試應用程式
熱重載應用程式,查看首次使用 Material Checkbox 小工具算繪的核取方塊區塊:

12. 恭喜
恭喜!您與 Google Antigravity 合作,建構了 Flutter 文件檢視器,採用 Dart 3 記錄、模式、強化 switch 運算式和 sealed 類別。
建構內容
- 使用記錄傳回多個值:從
Document.metadata傳回位置和具名欄位 ((String, {DateTime modified})),並使用final (title, :modified) = document.metadata;將其解構為本機變數。 - 安全 JSON 驗證和擷取:使用可駁斥的
if-case陳述式和switch運算式,搭配巢狀對應模式,在單一運算式中驗證類型、檢查鍵和擷取值。 - 表現力豐富的 UI 分支:使用
switch運算式、物件模式 (Duration(inDays: final days)) 和when保護子句,設定相對時間戳記的格式,並建構內嵌小工具。 - 編譯時間完整性檢查:將文件內容區塊模擬為
sealed class Block階層 (HeaderBlock、ParagraphBlock和CheckboxBlock),讓編譯器確保每個區塊類型都能算繪。
後續步驟
請參閱 Dart 官方說明文件,瞭解更多模式類型、記錄功能和類別修飾符:
參考文件
如要深入瞭解本程式碼實驗室涵蓋的各項功能語言規格,請參閱原始 Dart 語言設計文件: