Dev.to AI 🤖 Ai 👁 0 📖 4 min read

Streaming markdown in Flutter without the jitter

If you have wired a model stream straight into a Flutter Text widget, you have met the three failure modes. The text jumps on bursty deltas: the network hands you three words, pauses, then twenty. Raw asterisks flash bef

If you have wired a model stream straight into a Flutter Text widget, you have met the three failure modes. The text jumps on bursty deltas: the network hands you three words, pauses, then twenty. Raw asterisks flash before closing markers: **imp renders as literal text until ortant** lands half a second later. The layout shifts as a code fence opens: everything below reflows when

```

arrives, and reflows again when it closes.

I fixed all three by splitting the problem into three layers — a typewriter buffer, a tolerant parser and a renderer that owns the caret. Here is each one, with the parts that actually mattered.

Layer 1: a typewriter buffer that can catch up

Rendering every delta is the first mistake. Delivery is bursty; reading is steady. TypewriterController sits between the stream and the UI, keeps the target string, and moves a visible cursor towards it on the vsync ticker:

final typer = TypewriterController(
  vsync: this,
  charsPerSecond: 320,
  maxBacklogSeconds: 0.9,
);
typer.addListener(() => setState(() {}));

// for each text delta from the provider
typer.push(delta);

The interesting part is not the typing, it is the catch-up. A naive typewriter releases one character per tick no matter what, and a fast model outruns it forever — the reader is always looking at text from two seconds ago. So the rate is derived from the backlog instead of being fixed:

final backlogSeconds = remaining / charsPerSecond;
final rate = backlogSeconds > maxBacklogSeconds
    ? remaining / maxBacklogSeconds   // finish the backlog in 0.9 s
    : charsPerSecond;

A slow stream looks like typing; a fast stream looks like typing slightly faster, and never more than 0.9 seconds behind. skipToEnd() is the tap for people who do not want to watch it.

Layer 2: a parser that tolerates half-typed input

The asterisk flash is a parser problem, not a rendering one. A strict parser sees **imp as plain text, because the closing ** has not arrived yet.

The fix has two halves. Block level: an unclosed fence still produces a code block, flagged incomplete, so the block appears at the first character of its body instead of at the closing fence:

if (fence != null) {
  final body = <String>[];
  var closed = false;
  // ...read until the closing fence or the end of the text
  return MarkdownBlock(
    kind: MarkdownBlockKind.code,
    language: language,
    code: body.join('\n'),
    incomplete: !closed,
  );
}

Inline level: when the text is still streaming, an unmatched ** styles the rest of the run instead of showing itself. The reader never sees the markers — they see bold text that happens to be one word long for a moment.

final tokens = const InlineParser().parse(text, tolerant: isStreaming);

Every prefix of a document has to parse, so the test suite asserts exactly that: slice a mixed document at every index and expect the parser not to throw.

Layer 3: a renderer with a caret that is not a character

The caret was my first bug in production. The obvious implementation is the U+258D left-three-eighths block character appended as a TextSpan. It looked right on my phone and rendered as tofu on a device whose font did not carry block elements — on the one element that is visible in every single message.

It is a WidgetSpan now. A drawn 3.5 pt rounded rectangle cannot be missing from a font:

spans.add(WidgetSpan(
  alignment: PlaceholderAlignment.middle,
  child: Container(
    width: 3.5,
    height: fontSize * 1.15,
    decoration: BoxDecoration(
      color: accent,
      borderRadius: BorderRadius.circular(1.5),
    ),
  ),
));

Two other layout details are worth stealing. The caret belongs on the last text block, never on a code block, where it would jump between short lines. And a code block should scroll horizontally instead of wrapping by default: a wrapped code block changes height on every chunk and drags the scroll position with it.

The two problems that took the longest

Tables. A table that fits on the screen must not scroll, and one that does not fit must. Estimating column widths from character counts gets this wrong the moment the user changes the text scale, so the widths are measured with a TextPainter using the same style and TextScaler as the cells.

The 320 dp phone at 2× text scale. That is where everything breaks first: the model badge in the header, the duration next to a tool call, the composer. The kit's widget tests pump at that size and assert that no RenderFlex overflowed, which catches regressions that look fine on a 390 dp simulator.

What it looks like

The whole surface — reasoning panel, tool-call cards, streamed markdown, syntax-highlighted code, copy button — is about 4,700 lines across the model, parser, highlighter and widget layers, with 65 tests and zero third-party dependencies: no flutter_markdown, no flutter_highlight, no google_fonts, no state-management package.

I packaged it as StreamKit for Flutter ($2.90, one-time) because rewriting the same three layers in every project got old. The demo app runs offline from a scripted stream, so you can see every state without an API key.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.