Streaming LLM Responses in Flutter with Server-Sent Events
When a user sends a message to an AI model, waiting ten or twenty seconds for a complete reply feels slow. Streaming changes that experience: words appear in the chat as the model generates them, so the reader can start reading while the response is still being written. For a mobile app, this makes AI features feel responsive instead of frozen.
This article shows how to connect a Flutter app to a language-model endpoint that streams responses using Server-Sent Events (SSE), how to parse the event stream in Dart, and how to render incoming text in the UI as it arrives.
Why Stream AI Responses Instead of Waiting
A non-streaming AI request holds the connection open until the model finishes the entire answer. On a slow model or a long response, the user sees nothing but a loading spinner. Streaming moves the first visible text to the first token, which improves perceived performance even when the total time is unchanged.
Streaming also lets users act sooner. Someone reading a generated summary can decide the answer is enough and cancel the request before the model finishes. For chat interfaces, streaming is now the baseline expectation.
Prerequisites
You need the Flutter SDK, a code editor, and the http package for network requests.
You also need an LLM endpoint that supports Server-Sent Events. Many AI providers offer streaming,
but the exact event format, field names, and done markers vary by provider and by model version,
so check your provider's documentation before integrating.
This guide assumes you are comfortable with Dart async, Stream, and
Flutter StatefulWidget.
How Server-Sent Events Work
Server-Sent Events is a one-way protocol: the server keeps an HTTP connection open and pushes
text events to the client. The response uses the text/event-stream content type. Each
event consists of one or more lines like data: {...}, and events are separated by a
blank line. The client reads the connection incrementally instead of waiting for the full body.
A streaming AI endpoint usually sends one event per token or per chunk of text, then a final
event or connection close to signal completion. Some providers send a special marker such as
[DONE]; others simply close the stream. Your parser should handle both cases.
Step 1 — Add Dependencies and Configure the Client
dependencies:
flutter:
sdk: flutter
http: ^1.2.0
Create a dedicated client class so streaming logic stays out of your UI widgets. The example
below opens a POST request with a JSON body, sets the Accept header to
text/event-stream, and returns the raw byte stream.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class AiStreamClient {
final http.Client _client;
final Uri _endpoint;
AiStreamClient(this._endpoint) : _client = http.Client();
Future streamCompletion({
required String message,
required void Function(String chunk) onChunk,
}) async {
final request = http.Request('POST', _endpoint)
..headers['Content-Type'] = 'application/json'
..headers['Accept'] = 'text/event-stream'
..body = jsonEncode({'message': message, 'stream': true});
final response = await _client.send(request);
if (response.statusCode != 200) {
throw Exception('Stream request failed: ${response.statusCode}');
}
await for (final line in response.stream.transform(utf8.decoder).transform(const LineSplitter())) {
if (line.isEmpty) continue;
if (line.startsWith('data:')) {
final payload = line.substring(5).trim();
if (payload.isNotEmpty) {
onChunk(payload);
}
}
}
}
}
Step 2 — Parse Events and Handle Completion
The parser above treats every non-empty data: line as a new text chunk. Real
endpoints sometimes wrap the payload in JSON or send control events such as event: done.
Adjust the parser to match your provider's format, and never assume a chunk ends on a word
boundary: a single chunk can split a word in the middle.
Combine chunks into a growing string in your UI state. When the provider sends a completion marker or closes the connection, mark the stream as finished so the input field can be re-enabled.
class _ChatState extends State {
final StringBuffer _response = StringBuffer();
StreamSubscription? _subscription;
bool _streaming = false;
Future sendMessage(String message) async {
setState(() {
_response.clear();
_streaming = true;
});
final client = AiStreamClient(Uri.parse('https://api.example.com/complete'));
try {
await client.streamCompletion(
message: message,
onChunk: (chunk) {
setState(() => _response.write(chunk));
},
);
} catch (e) {
setState(() => _response.write('\nError: $e'));
} finally {
if (mounted) setState(() => _streaming = false);
}
}
}
Step 3 — Render Streaming Text in the UI
Update the UI on every chunk so the user sees tokens arrive in real time. A scrolling list
keeps the latest text visible. The example below renders the accumulated response inside a
SingleChildScrollView and shows a blinking cursor while streaming.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('AI Chat')),
body: Column(
children: [
Expanded(
child: SingleChildScrollView(
child: SelectableText(
_response.isEmpty ? 'Send a message to begin' : _response.toString(),
),
),
),
if (_streaming) const Text('Generating\u2026'),
TextField(
onSubmitted: sendMessage,
enabled: !_streaming,
),
],
),
);
}
Common Mistakes
- Treating chunks as complete sentences. Chunks can arrive mid-word. Append them to a buffer and render the whole buffer instead of replacing the UI text with each chunk.
- Forgetting to cancel the subscription. If the user navigates away while the stream is
open, cancel the
StreamSubscriptionindisposeto avoid memory leaks and set-state errors on unmounted widgets. - Ignoring connection errors. Mobile networks drop idle or weak connections. Wrap the stream in a try/catch, show a clear message, and offer a retry button instead of failing silently.
- Assuming every provider uses the same format. Some endpoints send JSON inside
data:lines, others send plain text, and the completion marker differs. Read your provider's stream documentation.
Trade-Offs: SSE Versus Alternatives
Server-Sent Events run over regular HTTP, which makes them easy to debug and compatible with standard proxies and firewalls. The downside is one-way communication only: the client receives events, but cannot push messages back on the same connection. For two-way real-time traffic, such as multi-user editing, WebSocket is the better fit.
On mobile, both can drop when the user enters a tunnel or backgrounds the app. Design the UI so an interrupted stream can be retried without losing the user's message.
Best Practices
- Send the authorization token in a request header, never in the URL query string.
- Set a read timeout appropriate for your model, and surface a timeout message instead of a spinner that spins forever.
- Show a caret or pulse animation while streaming so the user knows generation is still alive.
- Persist the completed response to local storage only after the stream finishes, so partial outputs are not mistaken for final answers.
- Validate and sanitize any dynamic content before rendering it, especially if the model output will be shown in a web view.
Conclusion
Streaming turns a slow AI request into an interactive experience. With Flutter and Server-Sent Events, you can show tokens as they arrive, handle connection problems gracefully, and keep users informed throughout the generation. Next: connect the client to a real endpoint, test on a real mobile network, and iterate.
FAQ
Does SSE work on both Android and iOS?
Yes. Server-Sent Events is standard HTTP, and Flutter's http package supports
streaming responses on both platforms.
Do I need a paid AI provider to use streaming?
No. Any endpoint that speaks text/event-stream works, including self-hosted
model servers, when cross-origin requests are allowed.
What happens if the user loses connection mid-stream?
The stream throws an error or ends early. Catch the error, show what was received so far, and offer a retry.
Can I send the user's message and API key in the URL?
No. Put the message in the request body and the API key in an authorization header; query strings are logged by proxies and are not safe for secrets.