1. Introduction
What you'll build
Imagine being asked whether it's possible to create the world's largest crossword puzzle. You recall some classic AI search techniques and wonder whether you can use Flutter to explore algorithmic solutions to computationally intensive problems while keeping the UI responsive at 60 fps.
In this codelab, you collaborate with Google Antigravity to build an algorithmic crossword generator and turn it into a playable word puzzle game. There are many definitions of a valid crossword puzzle, and the techniques you explore here help you generate puzzles that fit your rules.

With the crossword generator as a foundation, you then craft an interactive word puzzle game that runs across Android, iOS, Windows, macOS, and Linux:

Your learning journey
This codelab takes you through building the crossword generator and puzzle game step by step:
- Set up your Flutter environment - Configure the Flutter SDK and Google Antigravity for your target platform.
- Create a project - Prompt Antigravity to scaffold an empty Flutter project with
built_value,flutter_riverpod,two_dimensional_scrollables, andmaterial_ui. - Add words - Bundle the SOWPODS word list asset and load it eagerly at startup using an asynchronous Riverpod provider.
- Display the words in a grid - Define immutable
built_valuegrid models and render them in a 2DTableViewusing Riverpod'sselectfilter. - Enforce constraints - Validate interlocking crossword rules and move candidate placement off the UI thread with
compute. - Manage the work queue - Replace random placement with a backtracking
WorkQueuethat targets open intersection points. - Display statistics - Derive real-time generation metrics, elapsed time, and estimated remaining time in a floating HUD overlay.
- Parallelize with threads - Visualize active search cells and scale generation across a configurable pool of background worker isolates.
- Turn it into a game - Transform completed crosswords into an interactive multiple-choice word puzzle game.
What you'll learn
- How to collaborate with Google Antigravity to iteratively build and customize a compute-intensive Flutter application and word puzzle game.
- How to use background isolates to run expensive computations without blocking Flutter's render loop using Flutter's
computefunction and Riverpod'sselectrebuild filter. - How to model immutable data structures with
built_valueandbuilt_collectionto implement search-based Good Old-Fashioned AI (GOFAI) techniques like depth-first search and backtracking. - How to use the
two_dimensional_scrollablespackage to display large 2D grids smoothly.
Prerequisites
- Basic familiarity with Flutter and Dart syntax.
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 models, isolates, providers, and widgets, inspect the key patterns in the generated code, and optionally explore algorithmic or UI 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:
- Flutter SDK
- Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
- Compiler software for your chosen development target (for example, Visual Studio to target Windows, Xcode to target macOS or iOS, or Android Studio to target Android).
3. Create a project
Understanding the dependencies
Before creating the project, review the core packages that power the crossword generator:
built_valueandbuilt_collection: Generate immutable value types and collections that share memory across derived instances—essential for backtracking search and passing state safely across isolates.flutter_riverpod,riverpod, andriverpod_annotation: Provide reactive state management, stream providers, and fine-grained rebuild filtering withselect().two_dimensional_scrollables: Renders large 2D grids lazily on both axes usingTableView.builder.characters: Handles grapheme-cluster string iteration accurately.intl: Formats large word and cell counts in the statistics overlay.
Prompt Antigravity to create the project
- 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\). - In the Antigravity agent chat panel, send the following prompt to create the Flutter project, add the dependencies, and wire up the initial app:
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.
Understanding the generated code
Antigravity scaffolds the project with flutter create --empty, installs the runtime and code-generation packages in pubspec.yaml, and wraps your MaterialApp in a Riverpod ProviderScope in lib/main.dart:
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)),
),
),
),
),
);
}
Run and test the app
Run the app on your chosen target device. You should see a window displaying Hello, World! centered on the screen:

4. Add words
Building blocks for a crossword puzzle
A crossword is, at its heart, a list of words arranged across and down in an interlocking grid. Solving one word gives clues to the words that cross it. A great starting word list is the SOWPODS list (267,750 words) from Peter Norvig's Natural Language Corpus Data page.
In this step, you prompt Antigravity to download the word list into assets/words.txt, expose it using a generated Riverpod provider in lib/providers.dart, eagerly initialize that provider at app startup, and render all 267,750+ words in a scrolling ListView.
Prompt Antigravity to load and display the word list
Send the following prompt in 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`.
Understanding the generated code
Filtering the word list into an immutable BuiltSet
In lib/providers.dart, the @riverpod annotation marks wordList for code generation by riverpod_generator. It loads assets/words.txt asynchronously and normalizes entries to lowercase a-z strings longer than two letters:
@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)),
);
}
Eager provider initialization and AsyncValue.when
Riverpod providers are lazy by default—they only start loading when first read. In lib/widgets/crossword_generator_app.dart, _EagerInitialization watches wordListProvider near the root of the widget tree so the dictionary begins loading immediately on startup (see Eager initialization of providers).
Inside the Scaffold body, watching wordListProvider returns an AsyncValue. Its when method bridges the asynchronous future and the synchronous build method by handling data, error, and loading states:
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()),
);
Run and test the app
Perform a hot restart (since you added a new asset and updated main()). You should see a scrollable list of over 267,000 dictionary words:

5. Display the words in a grid
In this step, you define the core immutable data structures for a crossword puzzle in lib/model.dart using built_value and built_collection, stream randomly placed words from lib/providers.dart, and render the 2D character grid with TableView.builder from two_dimensional_scrollables.
Prompt Antigravity to build the grid model and TableView UI
Send the following prompt in 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`.
Understanding the generated code
Finalizing the character map with @BuiltValueHook
In lib/model.dart, a Crossword stores a BuiltList and a BuiltMap for fast (x, y) lookup by the UI. Annotated with @BuiltValueHook(finalizeBuilder: true), _fillCharacters automatically populates the characters map whenever a CrosswordBuilder builds a new Crossword instance:
@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,
),
);
}
}
}
}
Streaming intermediate results with async*
In lib/providers.dart, crossword is an async* generator function returning Stream. Because it watches both sizeProvider and wordListProvider at the top of the function, Riverpod automatically cancels and restarts the stream whenever the user picks a new grid size from the menu.
Cell-level rebuild filtering with Consumer and select()
In lib/widgets/crossword_widget.dart, rebuilding the entire TableView every time a word is added would waste significant CPU cycles. Instead, each TableViewCell wraps its child in a Consumer and uses crosswordProvider.select(...) to watch only the CrosswordCharacter? at that specific location:
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,
),
),
);
// ...
Only the cells whose character actually changed rebuild when a new Crossword is yielded.
Run and test the app
Hot restart the app. You'll see characters filling the grid and a settings gear menu in the top-right corner that lets you switch grid sizes:

Right now, words are placed at random coordinates with zero validation, so they overwrite each other chaotically. In the next step, you'll enforce real crossword rules.
6. Enforce constraints
What you're changing and why
Currently, Crossword.addWord accepts any word at any coordinate. To generate valid English-style crosswords, Crossword must verify that:
- No word is duplicated in the grid.
- Every character stays within
[0, width)and[0, height). - Every character belongs to an across word, a down word, or a valid intersection where both words share the same letter.
- Vertically adjacent characters belong to the same
downWord, and horizontally adjacent characters belong to the sameacrossWord(preventing unintended two-letter collisions side by side). - Every new word after the first overlaps with at least one existing word.
Checking these constraints thousands of times on the main isolate would block Flutter's 60 fps rendering loop. You'll offload candidate evaluation to a background isolate using Flutter's compute function in a dedicated lib/isolates.dart library.
Prompt Antigravity to validate word placement in a background isolate
Send the following prompt in 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`.
Understanding the generated code
Validating candidate words in Crossword.addWord
In lib/model.dart, addWord now returns Crossword?. Before rebuilding the Crossword, it checks that every character either lands on an empty cell or matches an intersecting word's character in the perpendicular direction, and verifies 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;
}
Why lib/isolates.dart is separated from lib/providers.dart
Background isolates can't share mutable objects tied to the main isolate, such as Riverpod's Ref or StreamProviderElement. If you call compute with a closure directly inside the @riverpod Stream provider function, Dart captures the surrounding provider context and throws an unsendable object error:
Invalid argument(s): Illegal argument in isolate message: object is unsendable - Library:'dart:async' Class: _Future
<- Instance of 'AutoDisposeStreamProviderElement<Crossword>'
Extracting exploreCrosswordSolutions into lib/isolates.dart ensures the closure passed to compute only captures immutable, isolate-sendable values (Crossword and the Dart record (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));
Run and test the app
Hot restart the app. Words now properly interlock across and down in the grid while the UI remains responsive:

Because the generator is still guessing random coordinates and random words, it places words slowly. In the next step, you'll guide the search with a work queue.
7. Manage the work queue
Understanding the search strategy
Instead of guessing random coordinates across the entire board, you can turn crossword generation into a guided backtracking search:
- Track open character cells that only belong to a single word (and don't have parallel neighbors blocking perpendicular placement) in a
WorkQueue. - Pick a candidate location from
locationsToTryand filtercandidateWordsto words that contain the letter already at that intersection. - Try placing matching words across the intersection. If a word fits, update the
WorkQueuewith the new crossword; if no word fits after 1,000 tries, mark the location as a knownbadLocationand remove it from the queue.
Prompt Antigravity to add WorkQueue and guided search
Send the following prompt in 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`.
Understanding the generated code
Identifying open intersection points in WorkQueue.from
In lib/model.dart, whenever a word is added to the crossword, WorkQueue.from scans the placed characters, removes any cell that is already part of two crossing words or adjacent to a parallel word, and maps the remaining cells to the perpendicular Direction needed for a crossing word:
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'),
},
});
Formatting durations with Dart 3 records and pattern matching
In lib/utils.dart, DurationFormat uses a switch expression over a 4-element record (inDays, inHours, inMinutes, inSeconds) to produce a human-readable duration string:
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',
};
}
}
Run and test the app
Hot restart the app. Your crossword generator now fills grids dramatically faster by targeting valid intersections and pruning dead ends:

Can you make it even faster? First, display real-time telemetry so you can see where the algorithm spends its time.
8. Display statistics
Why add statistics?
When optimizing an algorithm, real-time telemetry helps you see how fast the grid fills, how many candidate locations remain, and where bottlenecks occur. In this step, you expose Stream from lib/isolates.dart, compute live statistics and estimated remaining time in lib/providers.dart, and render a toggleable heads-up display (CrosswordInfoWidget) driven by a per-frame TickerBuilder.
Prompt Antigravity to display generation statistics
Send the following prompt in 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`.
Understanding the generated code
Keeping timing state alive with @Riverpod(keepAlive: true)
If the user hides CrosswordInfoWidget, nothing in the widget tree watches startTimeProvider or endTimeProvider. Annotating StartTime, EndTime, and ShowDisplayInfo with @Riverpod(keepAlive: true) in lib/providers.dart prevents Riverpod from auto-disposing their state when the overlay is hidden:
@Riverpod(keepAlive: true)
class StartTime extends _$StartTime {
@override
DateTime? build() => _start;
DateTime? _start;
void start() {
_start = DateTime.now();
ref.invalidateSelf();
}
}
Driving a live elapsed-time readout with TickerBuilder
In lib/widgets/ticker_builder.dart, TickerBuilder uses SingleTickerProviderStateMixin to trigger a rebuild on every frame while generation is in progress. In lib/widgets/crossword_info_widget.dart, a switch expression over (startTime, endTime) pairs TickerBuilder with pattern matching so only the elapsed-time text ticks during active generation, stopping automatically once endTime is recorded:
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,
),
},
Run and test the app
Hot restart the app. You now have a floating statistics overlay in the bottom-right corner and a Display Info toggle in the settings menu:

Notice how toward the end of a run, the numbers keep changing while the grid barely updates—the single worker is spending time eliminating remaining dead-end locations one by one. Next, you'll parallelize that search across multiple isolates.
9. Parallelize with threads
Visualizing and parallelizing the search
As the grid fills up, valid word placements become scarce and a single worker isolate spends most of its time checking dead ends. In this step, you:
- Highlight cells currently in
workQueue.locationsToTry(explorationCell) usingAnimatedContainerandAnimatedDefaultTextStyleinCrosswordWidgetso you can watch the search frontier in real time. - Refactor
lib/isolates.dartto fan out candidate searches across a pool ofmaxWorkerCountparallel worker isolates usingcomputeandcandidateGeneratorFutures.wait. - Add a
BackgroundWorkersselector to the settings menu and statistics overlay so you can experiment with worker counts from1to128.
Prompt Antigravity to highlight search cells and parallelize worker isolates
Send the following prompt in 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`.
Understanding the generated code
Animating the search frontier in CrosswordWidget
In lib/widgets/crossword_widget.dart, each cell watches a second selective boolean—whether its location is currently in workQueue.locationsToTry.keys—and smoothly animates its colors with AnimatedContainer and AnimatedDefaultTextStyle:

Fan-out and fan-in with top-level compute functions
In lib/isolates.dart, _generate and _generateCandidate are defined as top-level functions so they never capture unsendable state. _generate takes up to maxWorkerCount shuffled locations, launches a compute(_generateCandidate, ...) future for each location, and awaits all of them concurrently with candidateGeneratorFutures.wait:
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;
Passing Dart records like (workQueue.crossword, workQueue.candidateWords, location, direction) in and (Location, Direction, String?) out cleanly adapts multiple parameters to compute's single-message signature.
Run and test the app
Hot restart the app and open the settings menu in the top-right corner to adjust the grid size, toggle the statistics overlay, and switch the number of background worker isolates:

10. Turn it into a game
What you're building: a playable crossword puzzle
In this final step, you turn the crossword generator into a playable multiple-choice word puzzle game:
- Generate the puzzle: Use your multi-isolate generator to build a completed crossword in the background while displaying a pulsing grid of hidden
'•'cells (CrosswordGeneratorWidget). - Generate alternate word choices: For each word in the solved crossword,
CrosswordPuzzleGame.fromselects four random distractor words of the exact same length from the remaining dictionary. - Interactive word placement: Tapping any cell opens a
MenuAnchorcontext menu (CrosswordPuzzleWidget) listing the candidate Across and Down words. Players can place words in any order (requireOverlap: false), and conflicting choices are automatically disabled usingcanSelectWord. - Detect victory: When the player's selected words form a valid crossword matching the word count of the generated puzzle, the app transitions to
PuzzleCompletedWidget.
Prompt Antigravity to turn the generator into a playable game
Send the following prompt in 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`.
Understanding the generated code
Offloading game state transitions with trampoline functions
Constructing CrosswordPuzzleGame.from (which searches the dictionary for distractor words) and validating selectWord are both CPU-intensive operations. In lib/providers.dart, the Puzzle notifier offloads both calls to compute using top-level trampoline functions so Puzzle's this reference is never captured by an isolate closure:
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);
Interactive cell menus in CrosswordPuzzleWidget
In lib/widgets/crossword_puzzle_widget.dart, each occupied cell combines the true across or down word with its four alternates into sorted BuiltList menus inside a MenuAnchor. Each _WordSelectMenuItem uses puzzleProvider.select(...) to enable or disable the button based on whether that word currently fits with the player's already-placed words:
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,
// ...
Run and test the app
Hot restart the app. Watch the generator animate the puzzle layout with '•' markers, then tap cells on the blank crossword grid to select interlocking Across and Down words (try switching to the 20 x 11 small grid in the settings menu for a quick solve). Once every word is placed validly, the app displays the completion screen:

11. Congratulations
Congratulations! You collaborated with Google Antigravity to build a multi-isolate crossword generator and word puzzle game in Flutter.
What you've built
- Loaded and filtered a 267,750+ word dictionary using eager Riverpod provider initialization.
- Modeled immutable crossword grids, work queues, and game states with
built_valueandbuilt_collection. - Implemented a backtracking constraint-satisfaction algorithm and scaled it across a pool of background worker isolates with
compute. - Rendered large 2D grids at 60 fps using
TableView.builderfromtwo_dimensional_scrollablesand cell-scopedselect()rebuild filters.