r/FlutterDev • • 2d ago

Discussion Three problems I hit streaming AI text into Flutter, and how I fixed them

I have been building a streaming chat UI in Flutter and hit three problems that only appear once tokens arrive in bursts.

1. Rebuilding on every delta. Each chunk triggered a setState and a full markdown re-parse; a fast stream meant many rebuilds per frame. Reveal now lives in a TypewriterController driven by a vsync ticker. It releases text at 320 chars/s, and when the backlog would take longer than ~0.9 s it raises the rate so it never falls permanently behind. skipToEnd() finishes instantly.

2. Partial markdown flickers. A half-arrived **bold run renders as literal asterisks until the closing marker lands, then snaps. The parser never throws on any prefix of the document: an unclosed fence still renders as a code block flagged incomplete, and tolerant mode styles an unclosed ** run instead of showing it.

3. The caret. I used the U+258D block glyph first — it rendered as tofu on a device whose font did not carry block elements. It is a WidgetSpan now, a drawn rectangle that cannot be missing from a font. I check the layout at 320 dp with 2× text scale, which is where the model badge and the composer break first.

65 tests, zero dependencies beyond the Flutter SDK, Flutter 3.22+.

Two smaller things took longer than expected: a table that fits must not scroll while a wide one must (column widths measured with a TextPainter at the same text scale as the cells), and a code block scrolls horizontally instead of wrapping, because a wrapped block changes height on every chunk and drags the scroll position with it.

Screens of the component set are here if you want to compare them with your own: https://github.com/StephenColor/flutter-streaming-markdown-kit (~4.7k lines, showcase repo only — the source itself is not public).

2 Upvotes

10 comments sorted by

1

u/Fluid-Court-6508 2d ago

The vsync ticker approach for the typewriter is clever, I've been meaning to move away from just calling setState on every chunk and this gives me a solid direction to try. That tofu issue with the block glyph is the kind of thing you never catch in testing until a random device shows up with a stripped-down font set. The table text scale trick seems like the sort of thing you only figure out after a few days of banging your head against a wall.

1

u/stephencolor 1d ago

Thanks! The tofu came from a cheap Android phone with a stripped font set — fine in the emulator, a box on the device. Anything the framework draws instead of a font character is one less per-device failure to chase. Same reason the table measurement reads MediaQuery.textScalerOf(context): measure at the scale the cell will actually be painted at, or the columns drift apart the moment someone turns text size up.

1

u/MobileXapps 2d ago

Two things that usually show up next: screen readers announcing every delta, and text selection jumping while the stream is still running. I'd keep the semantics label on the finished message only, and pause the reveal while the user has an active selection.

Also scroll anchoring. If someone scrolls up to reread, new tokens shouldn't pull them back down.

1

u/stephencolor 1d ago

All three are fair, and honestly none of them are really handled yet. On screen readers: nothing explicit on the answer text, so TalkBack and VoiceOver just read the markdown as it grows, which is the delta-by-delta behaviour you mean — the pieces that do carry labels are chrome (composer, thinking panel, the streaming dots, tool cards). What you describe is what I want: keep the streaming text out of the semantics tree while it moves, publish the finished message once with a single label, and say something while it is still generating. On selection, nothing is selectable yet — there is no SelectionArea around the blocks — so there is no jitter, because there is no selection; that is the easy half, and once it exists, pausing the reveal on a non-collapsed selection and not dropping it on rebuild is the plan. On scroll anchoring, that one is just a bug in the demo: it jumps to maxScrollExtent on every tick, unconditionally, so scrolling up to reread pulls you back down. The fix is the usual one — follow only while you are already near the bottom, otherwise keep the block you are reading pinned.

1

u/laplace_apps 2d ago

Scrolling code blocks horizontally instead of wrapping so the height doesn't jump on every chunk is a subtle one, nice. One idea if long replies ever get heavy: cache the parsed output for blocks that are already closed and only re-parse the last, still-growing block. Earlier paragraphs never change, so parse cost stays flat however long the message gets. Do you re-parse the full document each tick right now?

1

u/stephencolor 1d ago

Yep, full re-parse on every rebuild — no block cache yet. What makes it survivable is the typewriter: the visible string only changes on a vsync tick, so at 320 chars/s it's roughly 5 chars per frame, i.e. one parse per frame instead of one per token delta. The parse itself is linear in the message (one split on newlines, then a handful of line regexes, no backtracking traps), so a 2–3k char answer has been fine and in my profiles layout dominates, not the parse. But it is still O(n) every frame, which is the wrong shape as replies get long, so your idea is on my list. The part I have not worked out cleanly is detecting a stable block boundary cheaply: a blank line or a fence terminator is reliable, but a paragraph that is mid-word is not, and a table's last row is legitimately still growing.

1

u/No_Boss_1911 1d ago

the backlog speedup thing is smart. I hit almost the same rebuild mess but my replies also get read out loud by a tts voice, and the rule i cant break is the text on screen never gets ahead of what the voice is saying. if it does people read ahead and the voice feels laggy

so for me the release rate cant be a fixed 320 chars/s, it has to follow the audio position. can TypewriterController take an outside clock or do i just pause/resume it off the player? also what happens to an unclosed code fence if the user hits stop mid stream, does it stay an incomplete block or close itself

1

u/stephencolor 15h ago

Not today, and the honest answer is that it also has nothing to pause. TypewriterController is driven by its own vsync Ticker; the surface is push(chunk), setText (instant, no reveal), skipToEnd(), clear(), plus charsPerSecond and maxBacklogSeconds fixed at construction. There is no pause/resume in it, so pausing it off the player would mean owning the ticker yourself.

It would also fight you: the rate is not fixed at 320. When the backlog would take longer than maxBacklogSeconds (0.9 s) it raises the rate to catch up, which is exactly the behaviour you cannot have under a voice.

Two ways that do work. The cheap one is to gate the input: only push text the voice has already reached, using your TTS word or sentence boundary callbacks. The target then never runs ahead of the audio and the reveal still smooths each chunk, but you lose the burst hiding between chunks, and a seek needs setText to resync. The proper one is a position hook: let the audio position set the revealed index, snapped to grapheme boundaries, with the parser only ever seeing whole characters. That is a small API (syncTo(Duration position)) next to a word-timing list from the TTS, and it is how I would build karaoke-style highlighting. Not in the kit yet.

On the fence: it stays unclosed. The parser returns it as a code block with incomplete: true; that flag comes from the closing fence not being found, not from whether streaming is on. The body keeps whatever arrived, and nothing is auto-terminated or dropped. One catch: the "Streaming" chip under the block is driven by that same flag and the view passes it through regardless of isStreaming, so after a stop it would still be showing. Small fix (suppress it once the message is no longer streaming), and it is on my list.

0

u/[deleted] 2d ago

[removed] — view removed comment

1

u/stephencolor 1d ago

No cache and no debounce at the moment — it measures inline in build, one TextPainter per cell, laid out at maxLines: 1 with the same textScaler the cells are painted at, then disposed. It stays cheap because chat tables are small: three or four columns with a handful of rows is a dozen painters per frame, and it only runs when the widget rebuilds, so once per vsync tick while streaming. A wide table with long cells is where it would start to show. I skipped debounce deliberately: holding stale widths means the columns snap a moment later, which is the same jitter moved rather than removed. A cache keyed on cell text + style + textScaler is the version I would ship if someone threw a 10-column table at it.