1. 简介
构建内容
想象一下,如果有人问您是否可以创建世界上最大的填字游戏,您会怎么回答?您回想起了一些经典的 AI 搜索技术,并想知道是否可以使用 Flutter 探索计算密集型问题的算法解决方案,同时保持界面以 60 fps 的速度响应。
在此 Codelab 中,您将与 Google Antigravity 协作,构建一个算法填字游戏生成器,并将其转化为一款可玩的益智游戏。有效的填字游戏有许多定义,您在此处探索的技术可帮助您生成符合您规则的游戏。

以填字游戏生成器为基础,您将打造一款可在 Android、iOS、Windows、macOS 和 Linux 上运行的互动式字谜游戏:

您的学习之旅
本 Codelab 将引导您逐步构建填字游戏生成器和益智游戏:
- 设置 Flutter 环境 - 为目标平台配置 Flutter SDK 和 Google Antigravity。
- 创建项目 - 提示 Antigravity 使用
built_value、flutter_riverpod、two_dimensional_scrollables和material_ui构建一个空的 Flutter 项目。 - 添加字词 - 捆绑 SOWPODS 字词列表资源,并在启动时使用异步 Riverpod 提供程序预先加载该资源。
- 在网格中显示单词 - 定义不可变的
built_value网格模型,并使用 Riverpod 的select过滤器在 2DTableView中呈现这些模型。 - 强制执行约束条件 - 验证连锁填字游戏规则,并使用
compute将候选位置移出界面线程。 - 管理工作队列 - 将随机放置替换为针对开放交叉点的回溯
WorkQueue。 - 显示统计信息 - 在浮动 HUD 叠加层中获取实时生成指标、已用时间和预计剩余时间。
- 使用线程实现并行化 - 直观呈现活跃搜索单元,并在一组可配置的后台工作器隔离区中扩缩生成。
- 游戏化 - 将完成的填字游戏转换为互动式多选题字谜游戏。
学习内容
- 如何与 Google Antigravity 协作,以迭代方式构建和自定义计算密集型 Flutter 应用和益智游戏。
- 如何使用后台隔离区运行高开销计算,而不会使用 Flutter 的
compute函数和 Riverpod 的select重新构建过滤器来阻塞 Flutter 的渲染循环。 - 如何使用
built_value和built_collection对不可变数据结构进行建模,以实现基于搜索的传统 AI (GOFAI) 技术,例如深度优先搜索和回溯。 - 如何使用
two_dimensional_scrollables软件包流畅地显示大型 2D 网格。
前提条件
- 基本熟悉 Flutter 和 Dart 语法。
2. 设置您的 Flutter 环境
编辑者
此 Codelab 使用 Google Antigravity 作为 AI 优先的开发环境。在每个步骤中,您都会提示 Antigravity 生成或演进应用的模型、隔离区、提供程序和 widget,检查生成的代码中的关键模式,并视需要探索算法或界面变体。
安装 Flutter
如需获取关于如何安装 Flutter SDK 的最新说明,请随时访问 docs.flutter.dev。
对于此 Codelab,请安装以下软件:
- Flutter SDK
- 已启用官方 Dart 和 Flutter 插件的 Google Antigravity(可在插件市场的 Build with Google 部分中找到)。
- 您选择的目标开发平台所需的编译器软件(例如:以 Windows 为目标开发平台时,需要 Visual Studio;以 macOS 或 iOS 为目标开发平台时,需要 Xcode;以 Android 为目标开发平台时,需要 Android Studio)。
3. 创建项目
了解依赖项
在创建项目之前,请先查看为填字游戏生成器提供支持的核心软件包:
built_value和built_collection:生成不可变的值类型和集合,这些类型和集合可在派生实例之间共享内存,这对于回溯搜索和在隔离区之间安全传递状态至关重要。flutter_riverpod、riverpod和riverpod_annotation:通过select()提供响应式状态管理、流提供程序和精细的重新构建过滤。two_dimensional_scrollables:使用TableView.builder在两个轴上延迟渲染大型 2D 网格。characters:准确处理字形集群字符串迭代。intl:在统计信息叠加层中设置大字数和单元格数的格式。
提示 Antigravity 创建项目
- 启动 Google Antigravity,然后打开一个空目录,用于构建项目(选择不需要提权或不包含空格的路径,例如主目录中的文件夹或
C:\src\)。 - 在 Antigravity 智能体对话面板中,发送以下提示,以创建 Flutter 项目、添加依赖项并关联初始应用:
Create a new empty Flutter project named `generate_crossword` targeting `macos,linux,windows,ios,android`. Add the dependencies `built_collection`, `built_value`, `characters`, `flutter_riverpod`, `intl`, `material_ui`, `riverpod`, `riverpod_annotation`, and `two_dimensional_scrollables`, along with the dev dependencies `build_runner`, `built_value_generator`, and `riverpod_generator`. Configure `analysis_options.yaml` to disable `strict-inference` and `prefer_const_constructors` and exclude `lib/*.g.dart`. Finally, update `lib/main.dart` (importing `package:material_ui/material_ui.dart`) to run a `MaterialApp` inside a `ProviderScope` with a `Colors.blueGrey` seed light theme, `debugShowCheckedModeBanner: false`, and a `Scaffold` showing `'Hello, World!'` centered in 24px text.
了解生成的代码
Antigravity 会使用 flutter create --empty 构建项目,在 pubspec.yaml 中安装运行时和代码生成软件包,并在 lib/main.dart 中将 MaterialApp 封装在 Riverpod ProviderScope 中:
void main() {
runApp(
ProviderScope(
child: MaterialApp(
title: 'Crossword Builder',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorSchemeSeed: Colors.blueGrey,
brightness: Brightness.light,
),
home: Scaffold(
body: Center(
child: Text('Hello, World!', style: TextStyle(fontSize: 24)),
),
),
),
),
);
}
运行并测试应用
在所选目标设备上运行应用。您应该会看到一个窗口,其中 Hello, World! 居中显示在屏幕上:

4. 添加字词
纵横字谜的组成要素
填字游戏的核心是一个由横向和纵向单词组成的网格,这些单词相互交错。解出一个单词后,您就可以获得与该单词交叉的其他单词的线索。Peter Norvig 的自然语言语料库数据页面中的 SOWPODS 列表(267,750 个单词)是一个很好的起始单词列表。
在此步骤中,您将提示 Antigravity 将单词列表下载到 assets/words.txt 中,使用 lib/providers.dart 中生成的 Riverpod 提供程序公开该列表,在应用启动时立即初始化该提供程序,并在滚动的 ListView 中呈现所有 267,750 多个单词。
提示 Antigravity 加载并显示字词列表
在 Antigravity 中发送以下提示:
Download the SOWPODS word list from `https://norvig.com/ngrams/sowpods.txt` into `assets/words.txt` and declare `assets/words.txt` under `flutter: assets:` in `pubspec.yaml`. Create `lib/providers.dart` (importing `package:riverpod_annotation/riverpod_annotation.dart` with `part 'providers.g.dart';`) and define a `@riverpod Future<BuiltSet<String>> wordList(Ref ref)` provider that loads `assets/words.txt` using `rootBundle.loadString`, splits lines with `LineSplitter`, and rebuilds a `BuiltSet<String>` of lowercase trimmed `[a-z]` words longer than 2 characters. Run `build_runner` to generate `lib/providers.g.dart`. Then create `CrosswordGeneratorApp` in `lib/widgets/crossword_generator_app.dart` (importing `package:material_ui/material_ui.dart`) wrapped in a private `_EagerInitialization` `ConsumerWidget` that watches `wordListProvider`, with an `AppBar` titled `'Crossword Generator'` and a `Consumer` body that uses `wordListAsync.when` to display a `ListView.builder` of words, an error message, or a `CircularProgressIndicator`. Update `lib/main.dart` to use `CrosswordGeneratorApp()` as `home`.
了解生成的代码
将字词列表过滤为不可变的 BuiltSet
在 lib/providers.dart 中,@riverpod 注解会标记 wordList,以便通过 riverpod_generator 生成代码。它会异步加载 assets/words.txt,并将条目标准化为长度超过两个字母的小写 a-z 字符串:
@riverpod
Future<BuiltSet<String>> wordList(Ref ref) async {
final re = RegExp(r'^[a-z]+$');
final words = await rootBundle.loadString('assets/words.txt');
return const LineSplitter()
.convert(words)
.toBuiltSet()
.rebuild(
(b) => b
..map((word) => word.toLowerCase().trim())
..where((word) => word.length > 2)
..where((word) => re.hasMatch(word)),
);
}
提供程序预先初始化和 AsyncValue.when
Riverpod 提供程序默认采用延迟加载机制,即仅在首次读取时才开始加载。在 lib/widgets/crossword_generator_app.dart 中,_EagerInitialization 会在 widget 树的根附近监视 wordListProvider,以便在启动时立即开始加载字典(请参阅提供程序的 Eager 初始化)。
在 Scaffold 正文内,监视 wordListProvider 会返回一个 AsyncValue。其 when 方法通过处理 data、error 和 loading 状态,在异步 future 和同步 build 方法之间架起桥梁:
final wordListAsync = ref.watch(wordListProvider);
return wordListAsync.when(
data: (wordList) => ListView.builder(
itemCount: wordList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(wordList.elementAt(index)));
},
),
error: (error, stackTrace) => Center(child: Text('$error')),
loading: () => Center(child: CircularProgressIndicator()),
);
运行并测试应用
执行热重启(因为您添加了新资源并更新了 main())。您应该会看到一个包含超过 267,000 个字典单词的可滚动列表:

5. 以网格形式显示单词
在此步骤中,您将使用 built_value 和 built_collection 在 lib/model.dart 中为填字游戏定义核心不可变数据结构,从 lib/providers.dart 流式传输随机放置的单词,并使用 two_dimensional_scrollables 中的 TableView.builder 渲染 2D 字符网格。
提示 Antigravity 构建网格模型和 TableView 界面
在 Antigravity 中发送以下提示:
Create `lib/model.dart` (with `part 'model.g.dart';`) defining immutable `built_value` classes for the crossword grid:
- `Location`: 0-based `x` and `y` getters, directional getters (`left`, `right`, `up`, `down`), offset methods (`leftOffset`, `rightOffset`, `upOffset`, `downOffset`), `prettyPrint()`, and `Location.at(int x, int y)`.
- `Direction`: enum with `across` and `down` (`toString() => name`).
- `CrosswordWord`: `word`, `location`, `direction`, `static int locationComparator(CrosswordWord a, CrosswordWord b)`, and `CrosswordWord.word(...)` factory.
- `CrosswordCharacter`: `character`, optional `acrossWord` and `downWord`, and `CrosswordCharacter.character(...)` factory.
- `Crossword`: `width`, `height`, `BuiltList<CrosswordWord> get words`, `BuiltMap<Location, CrosswordCharacter> get characters`, `Crossword addWord({required Location location, required String word, required Direction direction})`, a `@BuiltValueHook(finalizeBuilder: true) static void _fillCharacters(CrosswordBuilder b)` hook that populates `characters` from `words`, `prettyPrintCrossword()`, and `Crossword.crossword(...)` factory.
- Top-level `@SerializersFor([Location, Crossword, CrosswordWord, CrosswordCharacter]) final Serializers serializers = _$serializers;`.
Next, create `lib/utils.dart` with a `RandomElements<E> on BuiltSet<E>` extension (`E randomElement()`). In `lib/providers.dart`, add a `CrosswordSize` enum (`small` 20x11, `medium` 40x22, `large` 80x44, `xlarge` 160x88, `xxlarge` 500x500 with `label => '$width x $height'`), a `@Riverpod(keepAlive: true) class Size` notifier defaulting to `CrosswordSize.medium` with `setSize(CrosswordSize size)`, and a `@riverpod Stream<model.Crossword> crossword(Ref ref)` generator that places random words at random locations and directions every 100ms until 80% of cells are filled. Run `build_runner`. Finally, create `CrosswordWidget` in `lib/widgets/crossword_widget.dart` (importing `package:material_ui/material_ui.dart`) using `TableView.builder` (with 32px `FixedTableSpanExtent` spans and per-cell `Consumer`s watching `crosswordProvider.select(...)` for that cell's `Location`), and update `lib/widgets/crossword_generator_app.dart` to display `CrosswordWidget` in the body and a `_CrosswordGeneratorMenu` (`MenuAnchor`) in `AppBar.actions` to switch `CrosswordSize`.
了解生成的代码
使用 @BuiltValueHook 完成字符映射
在 lib/model.dart 中,Crossword 会存储 BuiltList 和 BuiltMap,以便界面快速执行 (x, y) 查找。使用 @BuiltValueHook(finalizeBuilder: true) 进行注解,每当 CrosswordBuilder 构建新的 Crossword 实例时,_fillCharacters 都会自动填充 characters 映射:
@BuiltValueHook(finalizeBuilder: true)
static void _fillCharacters(CrosswordBuilder b) {
b.characters.clear();
for (final word in b.words.build()) {
for (final (idx, character) in word.word.characters.indexed) {
switch (word.direction) {
case Direction.across:
b.characters.updateValue(
word.location.rightOffset(idx),
(b) => b.rebuild((bInner) => bInner.acrossWord.replace(word)),
ifAbsent: () => CrosswordCharacter.character(
acrossWord: word,
character: character,
),
);
case Direction.down:
b.characters.updateValue(
word.location.downOffset(idx),
(b) => b.rebuild((bInner) => bInner.downWord.replace(word)),
ifAbsent: () => CrosswordCharacter.character(
downWord: word,
character: character,
),
);
}
}
}
}
使用 async* 流式传输中间结果
在 lib/providers.dart 中,crossword 是一个返回 Stream 的 async* 生成器函数。由于 Riverpod 会在函数顶部同时监视 sizeProvider 和 wordListProvider,因此每当用户从菜单中选择新的网格尺寸时,Riverpod 都会自动取消并重启数据流。
使用 Consumer 和 select() 进行单元级重新构建过滤
在 lib/widgets/crossword_widget.dart 中,每次添加字词时都重新构建整个 TableView 会浪费大量 CPU 周期。相反,每个 TableViewCell 会将其子级封装在 Consumer 中,并使用 crosswordProvider.select(...) 仅监视该特定 location 处的 CrosswordCharacter?:
TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
final location = Location.at(vicinity.column, vicinity.row);
return TableViewCell(
child: Consumer(
builder: (context, ref, _) {
final character = ref.watch(
crosswordProvider.select(
(crosswordAsync) => crosswordAsync.when(
data: (crossword) => crossword.characters[location],
error: (error, stackTrace) => null,
loading: () => null,
),
),
);
// ...
当生成新的 Crossword 时,只有字符实际发生变化的单元格才会重组。
运行并测试应用
热重启应用。您会看到网格中填满了字符,右上角有一个设置齿轮菜单,可让您切换网格大小:

目前,单词会放置在随机坐标处,没有任何验证,因此它们会混乱地相互覆盖。在下一步中,您将强制执行真正的填字游戏规则。
6. 强制执行限制条件
您要更改的内容及原因
目前,Crossword.addWord 接受任何坐标处的任何字词。为了生成有效的英式填字游戏,Crossword 必须验证:
- 网格中没有重复的字词。
- 每个字符都介于
[0, width)和[0, height)之间。 - 每个字符都属于一个横向单词、一个纵向单词,或一个有效的交叉点(两个单词共享同一个字母)。
- 垂直相邻的字符属于同一个
downWord,水平相邻的字符属于同一个acrossWord(防止并排出现意外的双字母冲突)。 - 除第一个单词外,每个新单词都至少与一个现有单词重叠。
在主 isolate 上检查这些约束条件数千次会阻塞 Flutter 的 60 fps 渲染循环。您将使用专用 lib/isolates.dart 库中的 Flutter compute 函数,将候选评估工作分流到后台隔离区。
提示 Antigravity 在后台隔离区中验证字词位置
在 Antigravity 中发送以下提示:
Update `Crossword` in `lib/model.dart` to add a `bool get valid` getter that enforces English crossword constraints (no duplicate words, all characters within grid bounds and part of at least one word, vertical neighbors sharing the same `downWord`, and horizontal neighbors sharing the same `acrossWord`). Update `Crossword.addWord` to return `Crossword?`, returning `null` if the word is already in the crossword, conflicts with an existing character or same-direction word, fails to overlap an existing word when `words.isNotEmpty`, or produces an invalid candidate `Crossword`. Then create `lib/isolates.dart` with `Stream<Crossword> exploreCrosswordSolutions({required Crossword crossword, required BuiltSet<String> wordList}) async*` that uses `compute` to test random candidate word placements in a background isolate and yields valid `Crossword` updates until 80% of cells are filled. Update `crossword` in `lib/providers.dart` to delegate to `exploreCrosswordSolutions`, and run `build_runner`.
了解生成的代码
正在验证 Crossword.addWord 中的候选字词
在 lib/model.dart 中,addWord 现在会返回 Crossword?。在重新构建 Crossword 之前,它会检查每个字符是否落在空白单元格上,或者是否与垂直方向上相交单词的字符匹配,并验证 candidate.valid:
final candidate = rebuild(
(b) => b
..words.add(
CrosswordWord.word(
word: word,
direction: direction,
location: location,
),
),
);
if (candidate.valid) {
return candidate;
} else {
return null;
}
为什么lib/isolates.dart与lib/providers.dart分开
后台隔离区无法共享与主隔离区关联的可变对象,例如 Riverpod 的 Ref 或 StreamProviderElement。如果您在 @riverpod Stream 提供程序函数中直接使用闭包调用 compute,Dart 会捕获周围的提供程序上下文,并抛出无法发送的对象错误:
Invalid argument(s): Illegal argument in isolate message: object is unsendable - Library:'dart:async' Class: _Future
<- Instance of 'AutoDisposeStreamProviderElement<Crossword>'
将 exploreCrosswordSolutions 提取到 lib/isolates.dart 中可确保传递给 compute 的闭包仅捕获不可变、可隔离发送的值(Crossword 和 Dart 记录 (word, direction, location)):
var candidate = await compute(((String, Direction, Location) wordToAdd) {
final (word, direction, location) = wordToAdd;
return crossword.addWord(
word: word,
direction: direction,
location: location,
);
}, (word, direction, location));
运行并测试应用
热重启应用。现在,单词在网格中正确地横向和纵向交错,同时界面仍能保持响应:

由于生成器仍在猜测随机坐标和随机单词,因此放置单词的速度很慢。在下一步中,您将使用工作队列来引导搜索。
7. 管理工作队列
了解搜索策略
您可以将填字游戏生成过程转换为引导式回溯搜索,而不是在整个棋盘上猜测随机坐标:
- 在
WorkQueue中跟踪仅属于单个单词(并且没有平行相邻单元格阻碍垂直放置)的开放字符单元格。 - 从
locationsToTry中选择一个候选位置,然后过滤candidateWords,仅保留包含该交叉点已有字母的单词。 - 尝试在交叉点放置匹配的单词。如果某个单词合适,则使用新填字游戏更新
WorkQueue;如果尝试 1,000 次后仍没有合适的单词,则将该位置标记为已知badLocation,并将其从队列中移除。
提示 Antigravity 添加 WorkQueue 和引导式搜索
在 Antigravity 中发送以下提示:
Add a `WorkQueue` `built_value` class to `lib/model.dart` (and register it in `@SerializersFor`) with `Crossword get crossword`, `BuiltMap<Location, Direction> get locationsToTry`, `BuiltSet<Location> get badLocations`, `BuiltSet<String> get candidateWords`, `bool get isCompleted => locationsToTry.isEmpty || candidateWords.isEmpty`, a `static WorkQueue from({required Crossword crossword, required Iterable<String> candidateWords, required Location startLocation})` builder that seeds `(0, 0)` when empty or finds eligible single-word intersection cells when non-empty, `WorkQueue remove(Location location)`, and `WorkQueue updateFrom(Crossword crossword)`. Add a `DurationFormat on Duration` extension (`String get formatted`) in `lib/utils.dart` using a record pattern switch. Finally, update `exploreCrosswordSolutions` in `lib/isolates.dart` to drive generation using `WorkQueue`, filtering `candidateWords` to those containing the target character at the chosen location (trying up to 1,000 shuffled words per `compute` call) and logging the total generation time with `formatted`. Run `build_runner`.
了解生成的代码
正在识别“WorkQueue.from”中的开放交叉点
在 lib/model.dart 中,每当有单词添加到填字游戏中时,WorkQueue.from 都会扫描已放置的字符,移除已属于两个交叉单词或与平行单词相邻的所有单元格,并将剩余单元格映射到交叉单词所需的垂直 Direction:
b.locationsToTry.addAll({
location: switch ((character.acrossWord, character.downWord)) {
(null, null) => throw StateError('Character is not part of a word'),
(null, _) => Direction.across,
(_, null) => Direction.down,
(_, _) => throw StateError('Character is part of two words'),
},
});
使用 Dart 3 记录和模式匹配设置时长格式
在 lib/utils.dart 中,DurationFormat 对 4 元素记录 (inDays, inHours, inMinutes, inSeconds) 使用 switch 表达式,以生成人类可读的时长字符串:
extension DurationFormat on Duration {
String get formatted {
final hours = inHours.remainder(24).toString().padLeft(2, '0');
final minutes = inMinutes.remainder(60).toString().padLeft(2, '0');
final seconds = inSeconds.remainder(60).toString().padLeft(2, '0');
return switch ((inDays, inHours, inMinutes, inSeconds)) {
(0, 0, 0, _) => '${inSeconds}s',
(0, 0, _, _) => '$inMinutes:$seconds',
(0, _, _, _) => '$inHours:$minutes:$seconds',
_ => '$inDays days, $hours:$minutes:$seconds',
};
}
}
运行并测试应用
热重启应用。现在,您的填字游戏生成器会通过定位有效的交叉点并剪除死胡同,以极快的速度填充网格:

Can you make it even faster? 首先,显示实时遥测数据,以便您了解算法在哪些方面花费了时间。
8. 显示统计信息
为什么要添加统计信息?
在优化算法时,实时遥测可帮助您了解网格填充速度、剩余候选位置数量以及瓶颈发生的位置。在此步骤中,您将从 lib/isolates.dart 公开 Stream,在 lib/providers.dart 中计算实时统计信息和预计剩余时间,并渲染由每帧 TickerBuilder 驱动的可切换平视显示 (CrosswordInfoWidget)。
提示 Antigravity 显示生成统计信息
在 Antigravity 中发送以下提示:
Add a `DisplayInfo` `built_value` class to `lib/model.dart` (and add it to `@SerializersFor`) with `wordsInGridCount`, `candidateWordsCount`, `locationsToExploreCount`, `knownBadLocationsCount`, `gridFilledPercentage`, a `DisplayInfo.from({required WorkQueue workQueue})` factory using `NumberFormat.decimalPattern()` from `package:intl/intl.dart`, and `static DisplayInfo get empty`. Update `exploreCrosswordSolutions` in `lib/isolates.dart` to return `Stream<WorkQueue>` and yield `workQueue` on each iteration. In `lib/providers.dart` (importing `package:riverpod/riverpod.dart` for `select`), replace `crossword` with `@riverpod Stream<model.WorkQueue> workQueue(Ref ref)` and add `@Riverpod(keepAlive: true)` notifiers `StartTime`, `EndTime`, and `ShowDisplayInfo`, plus `@riverpod Duration expectedRemainingTime(Ref ref)` (using `_estimatedTotalCoverage = 0.54`) and `@riverpod class DisplayInfo` (watching `workQueueProvider.select(...)` and returning `model.DisplayInfo.from(workQueue: workQueue)` on `data` or `model.DisplayInfo.empty` on `error` or `loading`). Update `CrosswordWidget` to watch `workQueueProvider`. Then create `TickerBuilder` (`lib/widgets/ticker_builder.dart`) and `CrosswordInfoWidget` (`lib/widgets/crossword_info_widget.dart`, importing `package:material_ui/material_ui.dart`), and update `lib/widgets/crossword_generator_app.dart` to overlay `CrosswordInfoWidget` in a `Stack` when `showDisplayInfoProvider` is true and add a `'Display Info'` toggle to `_CrosswordGeneratorMenu`. Run `build_runner`.
了解生成的代码
使用 @Riverpod(keepAlive: true) 保持计时状态
如果用户隐藏 CrosswordInfoWidget,则 widget 树中没有任何内容会监视 startTimeProvider 或 endTimeProvider。在 lib/providers.dart 中使用 @Riverpod(keepAlive: true) 注解 StartTime、EndTime 和 ShowDisplayInfo,可防止 Riverpod 在叠加层隐藏时自动处置其状态:
@Riverpod(keepAlive: true)
class StartTime extends _$StartTime {
@override
DateTime? build() => _start;
DateTime? _start;
void start() {
_start = DateTime.now();
ref.invalidateSelf();
}
}
使用 TickerBuilder 驱动实时经过时间读数
在 lib/widgets/ticker_builder.dart 中,TickerBuilder 使用 SingleTickerProviderStateMixin 在生成过程中触发每帧重建。在 lib/widgets/crossword_info_widget.dart 中,(startTime, endTime) 上的 switch 表达式与模式匹配 TickerBuilder 配对,因此只有经过时间文本会在生成过程中跳动,并在记录 endTime 后自动停止:
switch ((startTime, endTime)) {
(null, _) => _CrosswordInfoRichText(
label: 'Time elapsed',
value: 'Not started yet',
),
(DateTime start, null) => TickerBuilder(
builder: (context) => _CrosswordInfoRichText(
label: 'Time elapsed',
value: DateTime.now().difference(start).formatted,
),
),
(DateTime start, DateTime end) => _CrosswordInfoRichText(
label: 'Completed in',
value: end.difference(start).formatted,
),
},
运行并测试应用
热重启应用。现在,右下角有一个浮动的统计信息叠加层,设置菜单中有一个显示信息切换开关:

请注意,在运行即将结束时,数字会不断变化,而网格几乎不会更新,因为单个工作器正在花费时间逐个消除剩余的死胡同位置。接下来,您将跨多个 isolate 并行执行该搜索。
9. 使用线程并行化
直观呈现和并行化搜索
随着网格被填满,有效的单词放置位置变得越来越少,单个工作器隔离区会花费大部分时间来检查死胡同。在此步骤中,您将执行以下操作:
- 使用
CrosswordWidget中的AnimatedContainer和AnimatedDefaultTextStyle突出显示当前位于workQueue.locationsToTry(explorationCell) 中的单元格,以便实时观察搜索边界。 - 重构
lib/isolates.dart,使用compute和candidateGeneratorFutures.wait将候选搜索扇出到由maxWorkerCount个并行工作器隔离区组成的池中。 - 向设置菜单和统计信息叠加层添加
BackgroundWorkers选择器,以便您可以尝试使用1到128的工作器数量。
提示 Antigravity 突出显示搜索单元格并并行化工作器隔离区
在 Antigravity 中发送以下提示:
Update `CrosswordWidget` in `lib/widgets/crossword_widget.dart` to watch whether each cell's `location` is in `workQueue.locationsToTry.keys` (`explorationCell`) and animate cell background and text colors using `AnimatedContainer` and `AnimatedDefaultTextStyle` (`Durations.extralong1`, `Curves.easeInOut`, inverting `primary` and `onPrimary` colors for exploration cells). Refactor `lib/isolates.dart` so `exploreCrosswordSolutions` accepts `required int maxWorkerCount` and calls `compute(_generate, (workQueue, maxWorkerCount))`, where top-level `_generate` dispatches up to `maxWorkerCount` parallel `compute(_generateCandidate, ...)` calls across shuffled locations, awaits `candidateGeneratorFutures.wait`, applies valid words, and removes failed locations (stopping each worker after 1,000 tries or 10 seconds). In `lib/providers.dart`, add the `BackgroundWorkers` enum (`one(1)` through `oneTwentyEight(128)`) and `@Riverpod(keepAlive: true) class WorkerCount` defaulting to `BackgroundWorkers.four`, pass `workers.count` to `exploreCrosswordSolutions`, display `'Max worker count'` in `CrosswordInfoWidget`, and add worker count radio options to `_CrosswordGeneratorMenu`. Run `build_runner`.
了解生成的代码
CrosswordWidget中的搜索前沿动画
在 lib/widgets/crossword_widget.dart 中,每个单元格都会监视第二个选择性布尔值(其 location 当前是否在 workQueue.locationsToTry.keys 中),并使用 AnimatedContainer 和 AnimatedDefaultTextStyle 为其颜色添加流畅的动画效果:

使用顶级 compute 函数进行扇出和扇入
在 lib/isolates.dart 中,_generate 和 _generateCandidate 被定义为顶级函数,因此它们永远不会捕获不可发送的状态。_generate 最多接受 maxWorkerCount 个经过随机排序的位置,为每个位置启动一个 compute(_generateCandidate, ...) future,并使用 candidateGeneratorFutures.wait 并发等待所有这些 future:
for (final location in locations) {
final direction = workQueue.locationsToTry[location]!;
candidateGeneratorFutures.add(
compute(_generateCandidate, (
workQueue.crossword,
workQueue.candidateWords,
location,
direction,
)),
);
}
final results = await candidateGeneratorFutures.wait;
传入 Dart 记录(如 (workQueue.crossword, workQueue.candidateWords, location, direction))和传出 Dart 记录(如 (Location, Direction, String?))可将多个参数完美地适配到 compute 的单消息签名。
运行并测试应用
热重启应用,然后打开右上角的设置菜单,调整网格大小、切换统计信息叠加层,以及切换后台工作器 isolate 的数量:

10. 将学习变成游戏
您要构建的内容:可玩的填字游戏
在最后一步中,您需要将填字游戏生成器转换为可玩的选择题式字谜游戏:
- 生成谜题:使用多隔离区生成器在后台构建完整的填字游戏,同时显示隐藏的
'•'单元格 (CrosswordGeneratorWidget) 的脉冲网格。 - 生成备选用词:对于已解填字游戏中的每个单词,
CrosswordPuzzleGame.from会从剩余字典中随机选择四个长度完全相同的干扰词。 - 互动式单词放置:点按任意单元格即可打开
MenuAnchor上下文菜单 (CrosswordPuzzleWidget),其中列出了候选的横向和纵向单词。玩家可以按任意顺序放置单词 (requireOverlap: false),系统会使用canSelectWord自动停用冲突的选项。 - 检测胜利:当玩家选择的单词形成与生成的谜题的单词数匹配的有效填字游戏时,应用会转换为
PuzzleCompletedWidget。
提示 Antigravity 将生成器转换为可玩的游戏
在 Antigravity 中发送以下提示:
Update `Crossword.addWord` in `lib/model.dart` to add `bool requireOverlap = true` (only requiring overlap when `requireOverlap` is true). Add the `CrosswordPuzzleGame` `built_value` class to `lib/model.dart` (and `@SerializersFor`) with `Crossword get crossword`, `BuiltMap<Location, BuiltMap<Direction, BuiltList<String>>> get alternateWords`, `BuiltList<CrosswordWord> get selectedWords`, `canSelectWord`, `selectWord`, `Crossword get crosswordFromSelectedWords`, `bool get solved`, and `factory CrosswordPuzzleGame.from({required Crossword crossword, required BuiltSet<String> candidateWords})` that picks 4 sorted alternate words of matching length for each word in the crossword.
Update `lib/providers.dart` to use `const backgroundWorkerCount = 4;` in `workQueue`, remove the statistics/timer/worker-count providers (and the `package:riverpod/riverpod.dart` import), and add `@riverpod class Puzzle extends _$Puzzle` (with top-level `_puzzleFromCrosswordTrampoline` and `_puzzleSelectWordTrampoline` functions for `compute`). Replace the files in `lib/widgets/` (importing `package:material_ui/material_ui.dart`) with `CrosswordPuzzleApp` (`lib/widgets/crossword_puzzle_app.dart`), `CrosswordGeneratorWidget` (`lib/widgets/crossword_generator_widget.dart`, displaying `'•'` for occupied cells while generating), `CrosswordPuzzleWidget` (`lib/widgets/crossword_puzzle_widget.dart`, with `MenuAnchor` and `_WordSelectMenuItem` per cell), and `PuzzleCompletedWidget` (`lib/widgets/puzzle_completed_widget.dart`). Finally, update `lib/main.dart` to run `CrosswordPuzzleApp()` with title `'Crossword Puzzle'`, and run `build_runner`.
了解生成的代码
使用蹦床函数分流游戏状态转换
构建 CrosswordPuzzleGame.from(在字典中搜索干扰词)和验证 selectWord 都是 CPU 密集型操作。在 lib/providers.dart 中,Puzzle 通知器使用顶级 trampoline 函数将这两个调用分流到 compute,因此 Puzzle 的 this 引用绝不会被隔离区闭包捕获:
Future<model.CrosswordPuzzleGame> _puzzleFromCrosswordTrampoline(
(model.Crossword, BuiltSet<String>) args,
) async =>
model.CrosswordPuzzleGame.from(crossword: args.$1, candidateWords: args.$2);
model.CrosswordPuzzleGame? _puzzleSelectWordTrampoline(
(model.CrosswordPuzzleGame, model.Location, String, model.Direction) args,
) => args.$1.selectWord(location: args.$2, word: args.$3, direction: args.$4);
CrosswordPuzzleWidget 中的互动式单元格菜单
在 lib/widgets/crossword_puzzle_widget.dart 中,每个已填入字母的单元格都会将正确的横向或纵向单词及其四个备选单词组合到 MenuAnchor 内已排序的 BuiltList 菜单中。每个 _WordSelectMenuItem 都会使用 puzzleProvider.select(...),根据该单词当前是否与玩家已放置的单词相符来启用或停用按钮:
return MenuItemButton(
onPressed:
ref.watch(
puzzleProvider.select(
(puzzle) => puzzle.canSelectWord(
location: location,
word: word,
direction: direction,
),
),
)
? () => notifier.selectWord(
location: location,
word: word,
direction: direction,
)
: null,
// ...
运行并测试应用
热重启应用。观察生成器如何使用 '•' 标记为填字游戏布局添加动画效果,然后点按空白填字游戏网格上的单元格,选择相互关联的横向和纵向单词(尝试在设置菜单中切换到 20 x 11 小网格,以便快速解题)。当每个单词都有效放置后,应用会显示完成屏幕:

11. 恭喜
恭喜!您与 Google Antigravity 合作,在 Flutter 中构建了一个多隔离区填字游戏生成器和字谜游戏。
您构建的内容
- 使用 Eager Riverpod 提供程序初始化加载并过滤了包含 267,750 多个单词的字典。
- 使用
built_value和built_collection对不可变的填字游戏网格、工作队列和游戏状态进行建模。 - 实现了一种回溯约束满足算法,并使用
compute将其扩展到后台工作器隔离池中。 - 使用
two_dimensional_scrollables中的TableView.builder和单元格范围的select()重新构建过滤器,以 60 fps 的速度渲染大型 2D 网格。