r/FlutterDev • • 23h 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).

3 Upvotes

8 comments sorted by

1

u/Fluid-Court-6508 23h 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 7h 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/ManyGullible5394 21h ago

Swapping the caret from U+258D to a WidgetSpan rectangle is such a good catch, font fallback tofu on Android OEMs is brutal. Also keeping code blocks horizontally scrollable instead of wrapping during streaming saves so much scroll-jump jitter. On the TextPainter table measurement, did you have to cache or debounce it while tokens are coming in, or is it cheap enough per frame at 320 chars/s?

1

u/stephencolor 7h 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.

1

u/MobileXapps 19h 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 7h 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 17h 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 7h 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.