Flutter

Real-Time Streaming in Flutter: WebSocket, SSE or WebRTC

You tap the mic button in your Flutter app, start talking, and the chat list behind it stops scrolling smoothly. Audio from the other side arrives in bursts an…

March 29, 2026•18 min read•By Stacklyn Labs
Real-Time Streaming in Flutter: WebSocket, SSE or WebRTC

You tap the mic button in your Flutter app, start talking, and the chat list behind it stops scrolling smoothly. Audio from the other side arrives in bursts and plays with gaps. DevTools shows red frames every time someone speaks. Or the stream is not voice at all: it is a chatbot screen that sits on a spinner until the whole answer is ready, then dumps it on screen in one go.

Both are real-time streaming in Flutter problems, and both usually start with the same mistake: choosing a transport before asking what kind of stream you have. This post goes in the order you should make the decisions. Pick the transport first: plain HTTP, Server-Sent Events, WebSocket or WebRTC. Then build the hardest common case, two-way voice over a WebSocket, with a worker isolate, Opus and a jitter buffer. Then the AI token stream, which needs far less machinery. Then the part every streaming feature needs and most tutorials skip: what happens to the data when the connection drops. That last part is the same problem an offline-first Flutter architecture solves for ordinary records.

Package versions are from pub.dev on November 30, 2026, codec numbers from the Opus RFCs and SSE behaviour from the WHATWG HTML spec. The code is a pattern sketch, not a drop-in library.

Choose the transport for real-time streaming in Flutter

Three questions decide it. Who talks: only the server, or both sides? Does a late packet still matter, or is late as bad as lost? Does your server need to see the media, to record it, transcribe it or moderate it?

Transport Direction Runs over Good for What it costs you
Plain HTTP Client pulls TCP Playing recorded audio or video, uploads No live back channel. A single upload that dies at 99% starts again unless you chunk it.
Server-Sent Events (SSE) Server to client only HTTP over TCP AI token streams, live feeds, progress updates Talking back needs a separate request. On Flutter mobile there is no built-in EventSource, so reconnects are your code.
WebSocket Both ways TCP Voice through your own server, chat, live app state, WebRTC signaling You own framing, heartbeats and reconnects. One lost TCP segment holds up every frame behind it.
WebRTC Both ways UDP where possible, relayed through TURN when not Low-latency calls, video, peer to peer A signaling server, STUN and TURN, and a relay bandwidth bill. Server-side recording needs a media server in the path.

If you are playing recorded audio, none of the live machinery below applies. An audio player package pulls the file over plain HTTP and buffers it for you.

If you are recording a long session, such as a 30-minute interview, POSTing one large file at the end puts the whole session at risk in the last minute of the upload. Streaming it as you record limits the loss to the seconds the connection was down, whichever streaming transport you pick.

For two-way voice where your server needs the audio, a WebSocket to your own backend is the pragmatic choice. The server receives every frame, so recording, transcription and moderation are just code on the server. WebRTC can do the same, but only with a media server or recording service sitting in the call. For one-way text from a model, SSE is enough. The rest of this post builds each case.

Why voice chat janks the UI

Flutter aims for 60 frames per second, which gives each frame about 16 ms. Your Dart code, layout and painting share one main isolate. Anything that keeps that isolate busy past the budget costs a frame.

Raw microphone audio is PCM. At 16 kHz, 16-bit, mono, that is 256 kbit/s; at 48 kHz it is 768 kbit/s. Opus, the codec WebRTC also uses, is built for this. RFC 7587 recommends 16 to 20 kbit/s for wideband speech, so encoding cuts the bytes by roughly 13 to 16 times before they touch the network.

Here is the part most voice chat tutorials get wrong. A single Opus encode is fast native code, and encoding one 20 ms frame will not blow a 16 ms budget. What hurts is volume. With 20 ms frames you encode 50 frames a second, decode 50 more, handle 100 socket events, and allocate a Uint8List for each, all on the isolate that is also laying out your chat list during a scroll. On a fast phone you get away with it. On older Android hardware you do not, and the same rules from Flutter performance on older Android devices apply here, at hundreds of small tasks a second.

There is a second trap. You cannot move the microphone itself into a background isolate. Flutter lets plugins run in background isolates through BackgroundIsolateBinaryMessenger, but the Flutter docs are explicit that a background isolate cannot receive unsolicited messages from the host platform. A microphone stream is exactly that. So capture stays on the main isolate, and everything after capture moves out.

Move encoding and the socket into a worker isolate

Use one long-lived worker, not Isolate.run per frame. Isolate.run spawns a fresh isolate for each call, and the Flutter docs note the spawn overhead makes long-lived isolates the better fit for repeated work. Then go one step further than most examples: let the worker own the WebSocket too. web_socket_channel's IO implementation is pure Dart on top of dart:io, so it runs in any isolate. Encoded audio never comes back through the main isolate at all.

On the main isolate, capture with the record package (7.2.0), which can stream raw PCM on Android, iOS and desktop. Check its defaults before you start: RecordConfig uses 44,100 Hz and two channels unless you say otherwise. Opus only accepts 8, 12, 16, 24 or 48 kHz, so the default rate will not encode at all.

import 'dart:async';
import 'dart:isolate';
import 'dart:typed_data';
import 'package:record/record.dart';

Future<SendPort> spawnVoiceWorker(SendPort toMain) async {
  final handshake = ReceivePort();
  await Isolate.spawn(voiceWorker, [handshake.sendPort, toMain]);
  return await handshake.first as SendPort; // the worker's inbox
}

Future<StreamSubscription<Uint8List>> startCapture(
  AudioRecorder recorder,
  SendPort toWorker,
) async {
  final mic = await recorder.startStream(const RecordConfig(
    encoder: AudioEncoder.pcm16bits,
    sampleRate: 16000, // Opus accepts 8, 12, 16, 24 or 48 kHz
    numChannels: 1,
  ));
  // Capture must stay on this isolate. Everything after it moves out.
  return mic.listen(toWorker.send);
}

SendPort.send copies a mutable Uint8List. At 640 bytes per 20 ms frame (16 kHz mono), that copy is not your problem. For large buffers, TransferableTypedData sends in constant time, though building one copies the bytes once.

The worker frames the PCM, encodes it, and writes to the socket:

import 'dart:async';
import 'package:web_socket_channel/io.dart';

Future<void> voiceWorker(List<Object> args) async {
  final handshake = args[0] as SendPort;
  final toMain = args[1] as SendPort;
  final inbox = ReceivePort();
  handshake.send(inbox.sendPort);

  final channel = IOWebSocketChannel.connect(
    Uri.parse('wss://api.example.com/voice'),
    pingInterval: const Duration(seconds: 10), // off by default
    connectTimeout: const Duration(seconds: 5), // default: never times out
  );
  try {
    await channel.ready;
  } catch (_) {
    toMain.send('connect_failed');
    return;
  }

  final framer = PcmFramer(bytesPerFrame: 640); // 20 ms, 16 kHz, mono, 16-bit
  final opus = createOpusCodec(sampleRate: 16000, channels: 1);
  final jitter = JitterBuffer();
  var seq = 0;

  inbox.listen((message) {
    if (message is Uint8List) {
      for (final frame in framer.add(message)) {
        channel.sink.add(withSeqHeader(seq++, opus.encode(frame)));
      }
    } else if (message == 'close') {
      channel.sink.close();
      Isolate.exit();
    }
  });

  channel.stream.listen((data) {
    if (data is Uint8List) {
      final (incomingSeq, payload) = readSeqHeader(data);
      jitter.push(incomingSeq, opus.decode(payload));
    }
  }, onDone: () => toMain.send('disconnected'));

  // The playback clock: one decoded frame to the main isolate every 20 ms.
  Timer.periodic(const Duration(milliseconds: 20), (_) {
    toMain.send(jitter.pop() ?? opus.conceal());
  });
}

PcmFramer, withSeqHeader and the codec wrapper are yours to write. The nearest Opus package on pub.dev is opus_dart 3.0.1, which wraps libopus and provides stream transformers from PCM to Opus and back. Its last release was about three years ago, so build it against your Flutter version before you commit to it, or write a thin FFI binding to libopus yourself. FFI works in background isolates.

Two limits to know about. Dart isolates do not exist on the web; Flutter web runs compute() on the main thread, so this design is for mobile and desktop. And Timer.periodic is not an audio clock. It drifts. If your playback package can pull frames on demand, let the audio output set the pace instead.

What TCP does to audio on a WebSocket

Many voice tutorials say the jitter buffer reorders packets that arrive out of order. Over a single WebSocket that does not happen. TCP delivers bytes in order. What TCP does instead is wait: when one segment is lost, every frame behind it is held until the retransmission arrives, and then they all land at once. Voice over a WebSocket fails as a stall followed by a burst, not as a shuffle.

A WebSocket keeps message boundaries (RFC 6455 binary frames), so one Opus packet per message needs no length prefix. You still want a sequence number in a small header, for three reasons. You need to spot the gap when a reconnect drops frames. Your server may fan audio from several senders into one socket. And the jitter buffer needs to know which frame is which after a burst.

The heartbeat matters more than it looks. pingInterval is null by default, which means no pings. A phone that switches from Wi-Fi to mobile data can leave a socket that looks open and carries nothing. With a ping interval set, a missing pong closes the socket, your onDone fires, and your reconnect code can run.

Build the jitter buffer

The jitter buffer sits between the socket and the speaker. Instead of playing each frame the moment it arrives, it waits until it holds a few frames, then releases one per 20 ms tick at a steady pace. Three frames (60 ms) is a reasonable starting depth; tune it on real networks. Deeper means fewer gaps and more delay.

It also has to handle the two failure shapes. On underrun, with nothing to play, it returns nothing and the decoder conceals the gap (Opus has built-in packet loss concealment). After a burst, it drops the oldest audio so a stall does not turn into a permanent delay.

import 'dart:collection';
import 'dart:typed_data';

class JitterBuffer {
  JitterBuffer({this.targetFrames = 3, this.maxFrames = 10});
  final int targetFrames;
  final int maxFrames;
  final _frames = SplayTreeMap<int, Uint8List>();
  bool _primed = false;
  int? _nextSeq;

  void push(int seq, Uint8List pcm) {
    if (_nextSeq != null && seq < _nextSeq!) return; // too late, already played past
    _frames[seq] = pcm;
    while (_frames.length > maxFrames) {
      _frames.remove(_frames.firstKey()); // after a burst, cut the delay
    }
    if (_frames.length >= targetFrames) _primed = true;
  }

  /// Null means "conceal this frame".
  Uint8List? pop() {
    if (_frames.isEmpty) {
      _primed = false; // underrun: refill before playing again
      return null;
    }
    if (!_primed) return null;
    final first = _frames.firstKey()!;
    var seq = _nextSeq ?? first;
    if (seq < first && first - seq > 2) seq = first; // gap too long to conceal
    _nextSeq = seq + 1;
    return _frames.remove(seq);
  }
}

On the main isolate, feed the frames to a player that accepts a live PCM stream. flutter_sound (9.30.0) can play from a Dart stream of PCM Int16 or Float32. Whatever you use, the main isolate's only job is to receive a frame and hand it to the player.

When WebRTC beats a WebSocket for voice

Everything in the last two sections exists because TCP waits for lost data. WebRTC sends media over UDP where it can, so a lost packet is simply gone and the next one plays on time. For a conversation, late is as useless as lost, which is why WebRTC is the standard for calls. RFC 7874 makes Opus and G.711 mandatory for WebRTC endpoints, and the native engine under flutter_webrtc (1.7.0) brings its own jitter buffer and loss concealment. The buffer code above becomes configuration.

The cost moves to the network edge. Phones sit behind NATs, so two devices cannot simply connect to each other:

  • Signaling. Before any audio flows, the two sides exchange session descriptions (SDP) and network candidates. WebRTC does not define how. You build it, usually over a WebSocket, so you need one anyway. Give every exchange a timeout and a retry; a signaling step that hangs forever is a common reason a call never starts.
  • STUN. A STUN server tells a device its public address so ICE can try a direct path.
  • TURN. When both sides are behind NATs with address-dependent or address-and-port-dependent mapping, a direct path fails and a TURN server relays the media. RFC 8656 is blunt that relaying is expensive for whoever runs the server. ICE tries direct paths first and uses TURN only when they fail, but production apps need TURN available.
import 'package:flutter_webrtc/flutter_webrtc.dart';

final pc = await createPeerConnection({
  'iceServers': [
    {'urls': 'stun:stun.example.com:3478'},
    {
      'urls': 'turn:turn.example.com:3478?transport=udp',
      'username': turnUser,       // short-lived credentials from your API
      'credential': turnPassword,
    },
  ],
});

pc.onIceConnectionState = (state) {
  if (state == RTCIceConnectionState.RTCIceConnectionStateFailed) {
    pc.restartIce(); // new candidates, which may now go through TURN
  }
};

Choose WebRTC for peer-to-peer calls, video, or anything where latency beats completeness. Stay on a WebSocket when the audio goes to your own server anyway, when you need every frame for recording or transcription, or when you do not want to run TURN. Plenty of products do both: WebRTC for the call, a WebSocket for signaling and chat.

Count what the voice path alone adds up to. Capture that respects plugin threading, a worker isolate with its own socket, sequence headers, a jitter buffer, reconnects with backoff and, if you go WebRTC, signaling plus a TURN server you pay to run. Each piece is small. Getting them to agree on flaky train Wi-Fi, and proving it in tests, is where weeks go before the first actual business feature ships. If a client wants live voice in their app and you would rather not carry that risk, we build real-time voice features in Flutter apps for agencies and founders.

Streaming AI tokens with Server-Sent Events

The chatbot case is simpler, and teams often overbuild it. Text flows one way, from model to user, so you do not need a WebSocket. Model APIs already stream this way. Anthropic's Messages API, for example, streams over SSE with content_block_delta events and may send ping events between them.

Do not call the model provider from the app. An API key compiled into a binary can be extracted. Put a small proxy in front of the provider: it authenticates your user, adds the key, applies rate limits, and forwards the event stream. Check every proxy and load balancer in that path for idle timeouts and response buffering. A buffering proxy quietly turns your stream back into one slow response.

On the Flutter side, the standard http package (1.6.0) is enough. Client.send gives you a StreamedResponse whose body arrives in chunks. The chunks split anywhere, including in the middle of a line or a multi-byte character, so parse by the spec rather than by chunk:

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

Stream<String> sseData(http.Client client, http.Request request) async* {
  final response = await client.send(request);
  if (response.statusCode != 200) {
    throw http.ClientException('SSE failed: ${response.statusCode}');
  }
  final data = StringBuffer();
  await for (final line in response.stream
      .transform(utf8.decoder)            // safe across split UTF-8 bytes
      .transform(const LineSplitter())) { // safe across split lines
    if (line.isEmpty) {                   // a blank line ends the event
      if (data.isNotEmpty) yield data.toString();
      data.clear();
    } else if (line.startsWith('data:')) {
      final value = line.substring(5);
      if (data.isNotEmpty) data.write('\n');
      data.write(value.startsWith(' ') ? value.substring(1) : value);
    }
    // event:, id: and retry: lines go here if your proxy sends them.
  }
}

The often-quoted advantage of SSE is automatic reconnection. That is true of the browser's EventSource: the spec has the client reconnect, wait the retry: interval, and send Last-Event-ID so the server can resume. A Flutter app on a phone using package:http gets none of that. When the stream ends early, your code decides whether to retry, and resuming only works if your proxy assigns event IDs and can replay from one. Many cannot, and the honest fallback is to show the partial answer and offer to regenerate.

Keep the UI rebuilds small. Calling setState on the whole conversation for every delta rebuilds every message bubble many times a second. Give the streaming message its own notifier or provider, and rebuild only that bubble.

Stream to cache: when the connection drops

Your connection will drop. The question is what the user loses when it does. A three-step pattern covers both cases in this post:

  1. Ingest. A provider listens to the stream: SSE deltas or decoded voice frames.
  2. Show it now. The UI reads from the provider in memory, so it never waits for disk.
  3. Commit on a timer. Writing to SQLite on every delta adds disk I/O many times a second. Accumulate the text and flush every 500 ms or so, plus once when the stream ends.

If the app is killed mid-answer, the user keeps everything up to the last flush. Reconnects use exponential backoff with some randomness, so every phone that lost signal in the same outage does not hit your server in the same second.

Voice needs a different answer than text. Live audio that arrives five seconds late is worthless to the listener, so do not queue missed live frames for replay. Drop them and reconnect. Queue audio only when the feature is a voice message or a recording, where every second matters more than timing. Then the compressed Opus frames go to local storage first and upload in order once the socket is back.

For that local store, the older advice was Isar. The original isar package's last stable release, 3.1.0+1, is about three years old, so do not start a new app on it. If you are already on it, our Isar alternative for Flutter comparison covers what to move to. For chat history and queued uploads, drift (2.35.4) gives you SQL, migrations and reactive queries.

If the stream is part of a business app that also has to keep working offline, we take on custom offline-first app development and send a fixed-price proposal within 24 hours, before any work starts.

Close everything when the screen closes

The user leaves the voice screen, the widget goes away, and the microphone, the worker isolate and the socket keep running. The battery drains, and the next visit opens a second socket next to the first.

Tie every resource to the lifetime of the provider that created it. In Riverpod (flutter_riverpod 3.5.0), ref.onDispose runs right before the provider is destroyed, including when an auto-dispose provider loses its last listener. Riverpod's docs recommend one onDispose call per resource:

ref.onDispose(micSubscription.cancel);
ref.onDispose(recorder.dispose);
ref.onDispose(() => toWorker.send('close')); // worker closes the socket, then exits
ref.onDispose(fromWorker.close);

Letting the worker close its own socket and call Isolate.exit is cleaner than killing it from outside. The server sees a proper close instead of a dead connection. If you use BLoC, the same rule applies in close(); our Riverpod vs BLoC in 2026 comparison covers how the two handle stream lifecycles.

Test streams without a server

A staging server in your unit tests gives you flaky tests. Every component above takes a Stream or exposes plain methods, so you can test it with fakes.

For the SSE parser, feed a Stream<List<int>> that splits an event in awkward places: mid-line, mid-character, with the blank line in its own chunk. For the socket layer, a StreamController<Uint8List> stands in for the WebSocket. Use Stream.periodic for steady arrival, then hold frames back and release them together to imitate a TCP stall. The jitter buffer needs no stream at all:

test('conceals one missing frame', () {
  final jb = JitterBuffer(targetFrames: 2);
  final frame = Uint8List(640);
  jb.push(0, frame);
  jb.push(1, frame);
  jb.push(3, frame);
  expect(jb.pop(), isNotNull); // 0
  expect(jb.pop(), isNotNull); // 1
  expect(jb.pop(), isNull);    // 2 missing: conceal
  expect(jb.pop(), isNotNull); // 3
});

Add cases for a long gap (it should skip ahead), a burst past maxFrames (it should drop the oldest), and a late frame (it should ignore it). These are the behaviours users hear, and they are deterministic once the network is out of the test.

Before you build any of this

If what you need is recorded audio streamed from a server rather than live voice, you can skip sockets entirely. Our Zenith sleep sounds app template streams all 45 of its tracks from cloud storage, using audio URLs you can point at your own server, CDN or GitHub storage, and plays them with just_audio, audio_service and audio_session. If your streaming feature writes to records that more than one device edits, read data synchronization and conflict resolution in offline apps next.

Stacklyn Labs
Written by Stacklyn Labs

Stacklyn Labs is a small studio publishing offline-first Flutter templates on CodeCanyon and Codester since 2025, and building custom Flutter and web apps for the teams who buy them.


More Articles

Related Posts

Marketplace Partner

Looking for Production-Ready Apps?

Save hundreds of development hours with our premium Flutter templates, Bootstrap web kits, and enterprise B2B source code.