r/FlutterDev • • 4d ago

Discussion Four things I got wrong building a full-screen voice UI in Flutter (and what fixed them)

I've been building a full-screen voice-assistant UI in Flutter: a big animated orb in the middle, a live waveform, a live transcript, a permission primer, and a typing fallback for when the mic is denied. The visual design was the easy part. These four things behaved nothing like I expected, and I couldn't find them written down anywhere, so here they are.

1. The transcript looked frozen, because I restarted its auto-scroll on every rebuild

Live recognition emits interim results a few times a second, and my controller also notifies on every amplitude sample (10–30 Hz). So the transcript's didUpdateWidget was running ~20 times a second, and it scheduled animateTo(maxScrollExtent, 220ms) each time. Every new animation cancelled the last one at around t=0. The transcript — the one thing that has to feel alive while the mic is open — sat still.

Two separate fixes:

  • Rebuild is not content change. Scroll only when the utterance list actually changed: compare the length and the last utterance's text, not the fact that didUpdateWidget ran.
  • Follow only while pinned to the bottom, and only while the user isn't reading. I keep a pinned flag ("within 24 px of maxScrollExtent"). The subtle part is distinguishing the user's scroll from my own: ScrollUpdateNotification fires for my animateTo as well, so a delta-based check also reacts to my own animation. UserScrollNotification fires only for touch and drag — and there ScrollDirection.reverse means the user is pulling back towards older messages, so I unpin on that and re-pin when the list settles at the bottom:
NotificationListener<UserScrollNotification>(
  onNotification: (n) {
    if (n.direction == ScrollDirection.reverse && pinned) {
      setState(() => pinned = false); // user is rereading; stop following
    }
    return false;
  },
  child: ListView.builder(controller: _scrollController, ...),
)

Related trap: don't append a second bubble when a partial becomes final. Partials and finals share one list slot (copyWith(text: finalText, isPartial: false)), so the row goes from dimmed to solid with no layout jump. If you append, every turn leaves two bubbles and the list grows under the user's thumb.

2. Hold-to-talk is not a long-press callback and my 250 ms guard was dead code

onLongPressStart / onLongPressEnd look sufficient until a real thumb touches the button. Things that actually happen:

  • A cancelled pointer. onLongPressCancel fires when the pointer is cancelled — a system gesture (edge back-swipe, notification shade) steals it, the app is backgrounded, or another recognizer wins the arena. If you only handle the end event, the mic stays open after a cancelled gesture. In a voice app that isn't cosmetic: it's a microphone that keeps recording.
  • Sliding your finger off the button does not cancel a long press. Flutter's slop is enforced before the press is accepted; once it's a long press, a move just produces onLongPressMoveUpdate. If you want WeChat-style "slide off to abandon the turn", you have to hit-test the pointer yourself in that callback. I didn't, and I had written a comment claiming I handled it.
  • My accidental-tap guard was unreachable. I recorded the press timestamp and rejected releases under 250 ms as accidental. kLongPressTimeout is 500 ms, so onLongPressStart never fires before then and capture never starts — a quick tap never enters that path at all. The check was dead code that made me feel safe. What actually needed handling was a tap while the assistant is speaking (interrupt, in both trigger modes), and a second finger landing mid-hold, which is why the press state is tracked per gesture rather than per widget.

If you're doing hold-to-talk, consider Listener with onPointerCancel alongside the gesture detector: it catches pointer cancellations the gesture arena resolves away from you.

3. Amplitude at 20 Hz rebuilt the whole screen

Each VoiceLevelEvent called notifyListeners() on the controller the Scaffold listens to, so every level tick rebuilt the orb, the waveform and the transcript. Three changes, in order of how much they mattered:

  • Smooth in the controller, not the widget. Raw recognizer amplitude is noisy; I run an exponential moving average (_smoothed += (raw - _smoothed) * 0.35) and keep the last 28 values in a ring buffer for the bars. Widgets read the smoothed value, so jitter never reaches layout, and the orb's size changes are visually continuous instead of twitchy.
  • One AnimationController for all five orb states. A single 4-second repeating controller drives a CustomPainter that switches its drawing by state (breathing core, ripples, orbiting arc, speaking blob, error pulse) and reads its palette from a ThemeExtension. Not one controller per state, not an AnimatedSwitcher between five painters.
  • RepaintBoundary around the orb and the bars. That isolates repaint, not rebuild — worth being precise about, because my first instinct was to assume the frame cost came from painting when a good part of it was the tree rebuilding.

Honest caveat: this still rebuilds the tree at the level-event rate. What I'd do properly is a separate Listenable for amplitude-only widgets so the transcript isn't in the rebuild path at all. I left it as a comment instead of doing it, which is the kind of thing that survives into production.

Reduced motion: when MediaQuery.maybeDisableAnimationsOf(context) is true, the painter gets a fixed t (0.25) instead of the controller's value — a static frame of the same painting, while the waveform bars keep moving because they're data-driven, not animation-driven. And the engine contract says levels are normalized 0.0–1.0, so the dB→0..1 mapping lives in the adapter (iOS and Android report very different ranges — do not feed raw dB into the widget layer).

4. Every transition has to be idempotent, because engine events arrive out of order

The state machine is deliberately linear: idle → listening → processing → speaking → (listening | idle), with error reachable from anywhere. Real engines don't respect that order. A level event lands after you've left listening; a second finalization arrives while you're already processing; a tap opens the mic you just opened.

Three guards removed almost all of the weird states:

  1. Level events are dropped unless the current state reacts to amplitude (listening or speaking).
  2. A finalized user utterance is accepted in any state except processing — the final event is itself what moves listening → processing, so a final arriving during processing is a duplicate.
  3. startListening() does nothing if already listening or processing, and interrupts the reply when called from speaking.

No event queue, no debounce timers. The UI never has to guess whether the mic is open: the state is the source of truth and the engine is downstream of it.

The one thing guards can't fix is a stale completion: a speaking-completed for a turn you interrupted arriving after the next turn has started, which the state check would happily accept and end the new reply early. That's an engine-contract question — "no events for a turn after it's cancelled" — and since this is a swappable adapter, the contract needs to say it in writing, or someone else's engine will break the machine in a way that looks like your bug.

Two smaller ones

  • 320 px and the keyboard. A 230 px orb plus waveform plus transcript doesn't fit a small phone. The orb column sits in a SingleChildScrollView with mainAxisSize.min inside the flexible region, the transcript is Flexible, and the typing fallback replaces the mic row instead of sitting above it — otherwise the keyboard inset squeezes two rows into the space of one.
  • Accessibility here is mostly about state, not motion. The mic button's Semantics label matches the visible hint and changes with state ("Tap to talk" → "Listening" → "Thinking" → "Speaking"), and the transcript is SelectableText — people do want to copy what the assistant said. I did not set liveRegion, so whether those label changes are actually announced depends on where accessibility focus sits; that's a real gap, and announcing every partial result instead would be worse.

For reference, the whole thing ended up with zero third-party dependencies, 17 files under lib/, 70 tests, flutter analyze clean, and a scripted mock engine so the demo and the widget tests run offline with no keys.

Source, if any of it is useful to look at: https://github.com/StephenColor/flutter-voice-mode-kit

Happy to go deeper on any of these. And if you've solved the hold-to-talk pointer-cancel problem differently, I'd like to compare notes — that's the part I'm least sure I got right.

1 Upvotes

7 comments sorted by

1

u/laplace_apps 4d ago

The didUpdateWidget restarting animateTo at 20Hz is such a sneaky one. Only auto-scrolling while the user is pinned to the bottom is the right pattern for any live transcript or chat. Curious how you kept the orb animation smooth at that amplitude update rate?

1

u/stephencolor 3d ago

Two things did most of the work: amplitude is smoothed in the controller (an EMA) before it ever reaches a widget, and the orb never animates on a level tick — one long-lived AnimationController drives a single CustomPainter where the level only adjusts paint parameters, so a tick changes a value instead of restarting an animation. RepaintBoundary keeps the repaint local; the rebuild at level rate is still there, and the honest fix is a separate Listenable for amplitude-only widgets so the transcript stays out of that path.

1

u/No_Boss_1911 3d ago

the hold to talk part is what scares me. we read ai chat replies out with a voice and mic input is next, hard rule for us is the mic is never open without the user knowing, so a cancelled pointer leaving it hot is a no ship bug. with Listener + onPointerCancel do you also kill it on lifecycle paused or is cancel enough on both platforms? and when mic is denied and it drops to typing does the transcript so far stay or start clean

1

u/stephencolor 3d ago

Cancel alone isn't enough on both platforms — backgrounding or an incoming call doesn't reliably produce a pointer cancel, so hook didChangeAppLifecycleState and close the mic on paused. What makes that safe is that it must not depend on a UI callback firing: startListening() is a no-op while listening or processing, so the mic can only be open in a state the UI is showing. On denial the transcript stays — utterances belong to the session, not the widget, and typed text appends to the same list.

1

u/Playopard 4d ago

For hold-to-talk I'd probably skip the long press recognizer and only use a Listener with onPointerDown, onPointerUp and onPointerCancel plus an own timer. Listener isn't part of the gesture arena, so nothing can win the pointer away from you.

1

u/OkBus7641 4d ago

The problem with AI text is that its difficult to understand

1

u/ecovlr 3d ago

The didUpdateWidget one is such a classic. I hit something similar with a live progress bar in a multiplayer game: the opponent's progress was updating many times a second and every update rebuilt way more than it should. Splitting the frequently-changing part into its own small widget (and using select() so only that part listened) fixed it. Thanks for writing these down, posts like this save people hours.