A command palette looks like a text field with a list under it. The list is the easy half. Everything that made mine take three rewrites was underneath the field: a ranking nobody could predict, results that arrived for a query the user had already left, and a keyboard that fought the caret.
I built it with no third-party packages — pure Dart scoring, a ChangeNotifier controller, widgets on top — and ran it at 320 dp with 3.0× text. These are the parts that only break once real data, real typing speed and a real keyboard are in the room.
1. The field is part of the score, not a tiebreaker
My first ranker searched the label, the subtitle and the body, and sorted by "how well did the query match". The result: typing new put a note whose third paragraph mentioned "new" above the New note command, because the note's match was contiguous and the command's was not.
The fix was to stop treating fields as equal:
const Map<_Field, int> _fieldWeight = {
_Field.label: 100,
_Field.keyword: 88,
_Field.subtitle: 76,
_Field.tag: 68,
};
final int weighted = score.score * _fieldWeight[field]! ~/ 100;
and to make the match kind dominate the score instead of being one term among many:
exact 400 · prefix 300 · word start 250 · acronym 200 · subsequence 60
+ 6 per character, + 14 per consecutive pair, + 8 per word boundary
- 2 per gap character, - length/2 (capped at 40)
Three consequences I had to accept on purpose:
- A prefix in the label (300) beats an exact hit in a tag (272). That is a product decision, not a maths accident. The user typed into a field that shows labels; the moment a tag can outrank the label, the list stops looking sorted.
- The length penalty is capped at 40. A 400-character title should not sink below a scattered subsequence, or long-titled notes disappear exactly when you need them.
- Recents cannot win. The recency/frequency boost is capped at 45 + 32 = 77, so a command used a hundred times still loses to one exact match at 400. Recents exist to order the empty field, not to outvote what someone just typed.
The "why is that first" bug has a second half: the user cannot see the reason. So the matcher returns the character ranges it scored, and the row renders them bold:
PaletteHighlight(text: item.label, spans: row.spans, style: labelStyle)
If a rank looks wrong, the highlight says which characters produced it. That turned ranking arguments into five-second conversations.
2. Case folding can change string length, so highlight offsets lie
The spans are computed on lowercased text and applied to the original string. In ASCII that is invisible. Then:
'İ'.toLowerCase().length // 2 — i + combining dot
'ß'.toLowerCase() // 'ss'
One extra code unit and every highlight in that row is off by one. Not a crash — a bold letter in the wrong place, which looks like a ranking bug and sends you hunting in the wrong file.
The guard is two lines: compute spans only when the folded string has the same length as the original, and drop them otherwise. The item still matches; it just doesn't claim to know where.
final bool sameLength = lowerText.length == text.length;
// spans are returned only when sameLength
Two smaller rules that came out of the same area:
-
Merge adjacent spans before drawing. A subsequence match on
csproduces two one-character spans; drawn separately they can pick up a hairline gap between bold glyphs. -
Clamp every span to the rendered string. Labels arrive translated, and a span computed for the English "New note" against the German "Neue Notiz" would otherwise throw inside
substring.
And one thing that behaved correctly but looked broken: a greedy left-to-right subsequence was matching cs against the first c and s of "Create snapshot" — which is right — but it also matched c and s inside a word when a word-start option existed two characters later. Adding a 3-character boundary lookahead fixed the highlight:
// prefer a word boundary within a short lookahead over the earliest hit
if (_isBoundary(text, j)) { chosen = j; break; }
if (fallback < 0) fallback = j;
if (j - cursor >= 3) break;
It is a heuristic, and I would rather have a heuristic I can read than a scoring model I cannot debug at 1 a.m.
3. "The older request will answer first" is false
The remote search is where the interesting bug lives. Mine debounced at 140 ms, then called the provider and merged the answer in. Type inv, pause, type oice: the first answer lands after the second one and overwrites it. The user sees results for a query that is no longer in the field.
Debouncing alone does not fix this. It only makes the race rarer. The fix is a generation token bumped on every keystroke and re-checked after every await:
void setQuery(String value) {
if (value == _query) return;
_query = value;
_parsed = ParsedQuery.parse(value);
_generation++;
_debounceTimer?.cancel();
_remoteItems = []; // local results stay, remote ones go
_searching = false;
if (_providers.isNotEmpty && _parsed.hasText) {
_debounceTimer = Timer(_debounce, _runProviders);
}
_rerank(keepHighlight: false);
notifyListeners();
}
Future<void> _runProviders() async {
final int generation = ++_generation; // this run invalidates any older one
final String snapshot = _query;
...
for (final provider in _providers) {
final answer = await Future.value(provider(snapshot));
if (_disposed || generation != _generation) return; // abandon, touch nothing
merged.addAll(answer);
}
}
The detail that cost me a debugging session: abandoning must mean abandoning everything, including _searching. The first version cleared the flag on the way out, so a stale run ending turned off the progress bar under a search that was still running. Returning before the flag is touched, and letting the current run own it, is the whole rule.
The regression test does the thing a network actually does — completes the older future last:
second.complete([fresh]); // the query the user is on
first.complete([stale]); // the query they left
// expect only 'fresh' in the results
Two more behaviours fall out of the same design:
- A failing provider is not a failed search. Errors are collected, the other providers' results are kept, and a retry banner sits above the local results instead of replacing them. Local ranking never depended on the network, so losing the network should cost you the archive, not the palette.
- Retry bumps the generation before it runs, so an answer from the query it replaced cannot land on top of the retry.
4. Arrow keys belong to the list, not the caret
A TextField owns the arrow keys. Bind ArrowDown inside or below it and the caret moves while the highlight stays still. The bindings have to sit above the field:
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.arrowDown): () => move(1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () => move(-1),
const SingleActivator(LogicalKeyboardKey.enter): submit,
const SingleActivator(LogicalKeyboardKey.escape): dismiss,
// left/right intentionally not bound: the caret keeps them
},
child: child,
);
Ctrl/Cmd+K is a different problem: it has to work when no field is focused, and it must not reach the field when one is. On a text field, Ctrl+K is a platform editing shortcut (kill to end of line on several bindings) — so opening a palette with it after a naive binding also deletes the rest of what you were writing. A hardware-level handler that returns true consumes it before the field:
HardwareKeyboard.instance.addHandler((KeyEvent event) {
if (event is! KeyDownEvent) return false; // repeat must not re-open
if (event.logicalKey != LogicalKeyboardKey.keyK) return false;
if (!kbd.isControlPressed && !kbd.isMetaPressed) return false;
widget.onOpen();
return true; // field never sees it
});
It must be removed in dispose, and it is global by design: mounted twice, it opens twice.
Keeping the keyboard honest is mostly bookkeeping:
- Disabled rows are sorted below every enabled row, whatever their score — a greyed row that ranks first is a trap for the person pressing Enter.
-
Navigation steps over disabled rows in a
do/whilethat can walk off the end. When every row is disabled the highlight simply stays put instead of landing on something that cannot run. -
The highlighted row is scrolled into view in a post-frame callback,
Scrollable.ensureVisible(alignment: 0.5, 120 ms). Two edge cases: theGlobalKeyfor a row built this frame has no context yet, and holding an arrow key queues one callback per row — so a_lastHighlightedguard collapses the burst into one scroll. -
A command runs once. The controller refuses a second activation while one is in flight (
PaletteStatus.busy), which is what keeps a double Enter or a fast tap from firing the same async command twice.
5. 320 dp at 3.0× text: what actually overflowed
Not the label — it is a single line with an ellipsis inside Expanded. The things that overflowed were the decorations around it:
-
The keyboard-hint chip on each row. Fixed
maxWidth: 88with an ellipsis, otherwiseShift+Cmd+Option+Ktakes the whole row at 3.0× and the label gets 20 dp. -
The footer.
↑↓ Navigate · Enter Run · Esc Closeplus38 resultsdoes not fit in 320 dp at 3.0×. Below400 dpthe words are dropped and only the key caps remain, the key group scrolls horizontally, and the count takes aFlexiblewith an ellipsis. The caps alone still say what to press.
final bool compact = constraints.maxWidth < 400;
-
The overlay height.
(height - top - keyboardInset - 24).clamp(240, 560)withtop = 88on tall screens and12on short ones. Without the clamp the panel is pushed under the keyboard on a 568 dp phone and the last row is unreachable; without the lower bound, a landscape phone gets a 90 dp panel.
The test harness is where most of this was found, and it needs three pieces to reproduce anything:
tester.view.physicalSize = size * 3; // 320 dp means 320 dp, not 107
tester.view.devicePixelRatio = 3;
// and text scale through MaterialApp.builder, so MediaQuery reaches the overlay
MediaQuery(data: MediaQuery.of(context).copyWith(
textScaler: TextScaler.linear(3)), child: child)
then expect(tester.takeException(), isNull) after pumping. Miss the dpr and the "narrow screen" case passes at 1× text on a device that never exists.
What is not in it
-
No IME awareness. During Korean or Chinese composition
onChangedfires with the composing text, so the provider sees half-formed queries. The 140 ms debounce hides most of it; the correct fix is to skip queries whilevalue.composing.isValidis true. - No highlight outside the label. A term that only matched the subtitle has no visible reason. Highlighting label characters that were not the ones matched would be worse, but "no highlight" is still an unexplained row.
- Recents are frequency, not context. The palette does not know that you are in a settings screen and rank settings commands higher. That needs a scope key on the usage store, which I have not written.
- The scoring weights are hand-tuned. 400/300/250/200/60 has no training data behind it. The tests pin the orderings rather than the constants so they can move, which is the honest version of "tuned".
The shape that held up
Pure-Dart core (dart:core only: query parser, matcher, ranker, usage), a controller that owns one generation counter and one busy flag, and widgets that never re-implement scoring. The core ranks a plain data class in tests and a PaletteItem in the app, and the widget layer never re-implements the matcher. 192 tests, flutter analyze clean, zero packages.
The README, nine screenshots and a demo GIF are in the showcase repo — no source in it, but the screen states are:
https://github.com/StephenColor/flutter-palette-kit
If you have built one of these, I would like to know how you handled the composition case in an IME, and whether your ranking survived a tag facet without a second pass over the results.
Top comments (0)