How to render streaming LLM output in Flutter
Updated 2026-11-17
The short answer
Accumulate the streamed text and pass it to GptMarkdown with isStreaming: true. gpt_markdown rebuilds only the part of the reply that is still changing, draws unfinished Markdown sensibly, and renders math and code in the same widget. For very long replies, use SliverGptMarkdown.
1. Install
bash
flutter pub add gpt_markdown2. Render the reply as it grows
Keep the text received so far in state and rebuild on each chunk. gpt_markdown does the rest: settled blocks are reused, so each update costs about the same whether the reply is 2 KB or 18 KB.
dart
String reply = '';
bool generating = true;
await for (final chunk in model.stream(prompt)) {
setState(() => reply += chunk);
}
setState(() => generating = false);
// In build():
GptMarkdown(
reply,
animation: GptMarkdownAnimation.fade,
isStreaming: generating,
)3. Long replies: lay out only what's on screen
dart
CustomScrollView(slivers: [
SliverGptMarkdown(reply),
])4. Links, selection and theming
- Links:
onLinkTap: (url, title) => launchUrl(Uri.parse(url)). - Selection: wrap the widget in
SelectionArea. - Theming: pass a
GptMarkdownStyleSheet(headings, code blocks, tables, links, math) or set it once with theGptMarkdownThemeDatatheme extension.
Common problems and fixes
| Problem | Cause | Fix |
|---|---|---|
| Frames drop as the reply gets long | The renderer re-parses the whole reply on every chunk | Use gpt_markdown (incremental), or SliverGptMarkdown for very long replies |
| Half a table or code fence flashes as raw text | The renderer only handles finished Markdown | gpt_markdown draws unfinished blocks while isStreaming is true |
| Math shows as $...$ text | No LaTeX support | gpt_markdown renders \(...\), \[...\] and, optionally, $...$ |
| setState() called after dispose() | The stream outlives the screen | Cancel the subscription in dispose() and check mounted |
Frequently asked
- How do I show a streaming AI response in Flutter?
- Append each chunk to a string in state and render it with GptMarkdown(reply, isStreaming: true). Set isStreaming to false when generation ends.
- Why does my Flutter chat lag on long replies?
- Most Markdown renderers re-render the whole document on every chunk, so the cost grows with the reply. gpt_markdown rebuilds only the live tail, and SliverGptMarkdown lays out only what is on screen.
- Does it work with any model?
- Yes. gpt_markdown renders text; it works with OpenAI, Anthropic, Google, local models or any stream of Markdown.