Home Best Practices How to Stream AI Responses in Flutter with Server-Sent Events

How to Stream AI Responses in Flutter with Server-Sent Events

11
0

When a Flutter chat app waits for the full AI response, the user spends the entire generation watching a loading indicator. With server-sent events (SSE), the app can display the first part of the answer while the model generates the rest. The improvement to measure is time to first visible text. The complete answer can still take just as long.

A typical setup sends the prompt from Flutter to an authenticated backend. The backend calls the model provider, keeps the provider API key on the server, and streams displayable text back to the phone. Dart’s package:http exposes the response body as a stream when the app uses Client.send().

1. Define the events your Flutter app will read

SSE uses a UTF-8 HTTP response with the text/event-stream content type. A blank line terminates an event. A network chunk can split an event or a character, so the app should decode the byte stream before parsing events. Dart’s UTF-8 decoder and LineSplitter handle those first two steps.

For text chat, three application events are enough:

EventFlutter behavior
deltaAdd text to the active assistant message
doneMark the message complete
generation-errorKeep the visible text and show a recovery action

The backend can translate OpenAI’s response.output_text.delta or Anthropic’s content_block_delta with a text_delta payload into the same app-level delta. Send done only after successful provider completion. If the connection closes first, the app can mark the reply as interrupted, even when most of the text has arrived.

2. Read the response with Dart’s HTTP client

Add the dependency with flutter pub add http. The helper below sends a JSON prompt to the chat endpoint, handles multiline SSE data, and yields text as each complete event arrives. It expects the three application events defined above.

import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart' as http;

Stream<String> streamReply({
  required Uri endpoint,
  required String prompt,
  required String sessionToken,
  required Future<void> abortTrigger,
}) async* {
  final client = http.Client();

  try {
    final request = http.AbortableRequest(
      'POST',
      endpoint,
      abortTrigger: abortTrigger,
    )
      ..headers.addAll({
        'Accept': 'text/event-stream',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer $sessionToken',
      })
      ..body = jsonEncode({'prompt': prompt});

    final response = await client.send(request);
    final contentType = (response.headers['content-type'] ?? '')
        .split(';')
        .first
        .trim()
        .toLowerCase();

    if (response.statusCode != 200 || contentType != 'text/event-stream') {
      throw StateError('Could not open chat stream (${response.statusCode})');
    }

    var event = '';
    final dataLines = <String>[];
    final lines = response.stream
        .transform(utf8.decoder)
        .transform(const LineSplitter());

    await for (final line in lines) {
      if (line.isEmpty) {
        if (dataLines.isNotEmpty) {
          if (event == 'done') return;
          if (event == 'generation-error') {
            throw StateError('Generation interrupted');
          }
          if (event == 'delta') {
            final payload = jsonDecode(dataLines.join('\n'));
            if (payload is! Map<String, dynamic> ||
                payload['text'] is! String) {
              throw const FormatException('Invalid text delta');
            }
            yield payload['text'] as String;
          }
        }

        event = '';
        dataLines.clear();
        continue;
      }

      if (line.startsWith(':')) continue;
      final separator = line.indexOf(':');
      final field = separator < 0 ? line : line.substring(0, separator);
      var value = separator < 0 ? '' : line.substring(separator + 1);
      if (value.startsWith(' ')) value = value.substring(1);

      if (field == 'event') event = value;
      if (field == 'data') dataLines.add(value);
    }

    throw StateError('Connection closed before completion');
  } finally {
    client.close();
  }
}

Create one Completer<void> per generation and pass its future as abortTrigger. When the user taps Stop, complete it once. On supported HTTP clients, package:http reports cancellation as RequestAbortedException, including when the app has already started reading the response. Handle that separately from a network failure and retain the text already displayed. The backend should also cancel its upstream model request when it detects the disconnect.

How five companies approach real-time and AI streaming

CompanyPublicly documented practice
GeekyAntsBuilt NowMatch with a Flutter frontend, BLoC state management, and a Hasura GraphQL data layer. The case study documents real-time Flutter architecture. Its relevance to an AI chat is the separation of incoming data from UI state.
GoogleFirebase AI Logic exposes generateContentStream for text generation and sendMessageStream for chat in Flutter. These SDK methods deliver partial Gemini responses to Dart code.
OpenAIThe Responses API exposes typed streaming events for text deltas, completion, and failures. A backend can map those events to a smaller contract that stays stable across mobile releases.
AnthropicThe Claude Messages API streams typed content blocks, pings, and errors over SSE. Text deltas can be routed to the chat bubble while other event types are handled separately.
CloudflareWorkers AI documents returning a streamed model response with Content-Type: text/event-stream, showing how an edge endpoint can relay output to an HTTP client.

What to test on iOS and Android

  • The full answer appears in one burst. Call the deployed endpoint with curl -N. If the terminal also receives everything at once, check whether the proxy buffers the response before investigating Flutter rendering.
  • The app backgrounds while a reply is streaming. Use AppLifecycleListener to check the generation’s status when the app returns. If replies must survive interruptions, persist the latest text under a generation ID. Repeating the original POST can start a second generation.
  • Long replies make scrolling feel sluggish. Buffer small text fragments and batch UI updates. Measure when the first delta arrives and when text first appears. A large gap points to work on the device, such as rebuilding the message list or re-parsing Markdown.
  • A broken stream looks complete. Use a test endpoint that splits UTF-8 characters across chunks, drops the connection before done, and delays the first event long enough to test Stop. The reference client above was checked against the Dart APIs, with device behavior left to integration testing.

Measure time to first visible text, time to completion, and interrupted replies together. A Flutter chat that shows text early and gives users a clear way to stop or recover delivers the practical benefit of SSE.

Previous articleHow to Test Flutter AI Applications Without Calling Live LLM APIs

LEAVE A REPLY

Please enter your comment!
Please enter your name here