Flutter and Dart
Use sockudo_flutter to add Sockudo realtime channels, presence, and Protocol V2 features to Flutter apps.
sockudo_flutter is the official Flutter and Dart realtime SDK for Sockudo. It keeps the Pusher
subscribe/bind model and adds Sockudo-native features: public, private, presence, and encrypted
channels, channel and user auth, Protocol V2 recovery and rewind, tag filters, Fossil and
Xdelta3/VCDIFF delta reconstruction, mutable messages, presence history proxies, and push
registration helpers.
The current package (2.2.0) requires Dart ^3.11.3 and Flutter 3.35+. Protocol V1
compatibility is the default; opt into Protocol V2 for Sockudo-native features.
Install
Install the published package from pub.dev:
flutter pub add sockudo_flutter# or, with the Dart CLI inside a Flutter project:dart pub add sockudo_flutterFor local monorepo development, use a path dependency instead:
dependencies: sockudo_flutter: path: ../sockudo/client-sdks/sockudo-flutterEverything is exported from a single library:
import 'package:sockudo_flutter/sockudo_flutter.dart';Connect
A SockudoClient owns one WebSocket connection to Sockudo. Channels are named streams multiplexed
over that connection: you subscribe to a channel, then bind callbacks to the event names published
on it. The client holds only your public app key; publishing and signing happen on your backend.
import 'package:sockudo_flutter/sockudo_flutter.dart';
final client = SockudoClient( 'app-key', const SockudoOptions( cluster: 'local', forceTls: false, enabledTransports: <SockudoTransport>[SockudoTransport.ws], wsHost: '127.0.0.1', wsPort: 6001, wssPort: 6001, protocolVersion: 2, connectionRecovery: true, ),);
void startRealtime() { client.bind('state_change', (change, _) { print('connection: ${change['previous']} -> ${change['current']}'); });
final channel = client.subscribe('public-updates'); channel.bind('price-updated', (data, _) { print(data); });
client.connect();}When the server accepts the connection, the state changes print in order:
connection: initialized -> connectingconnection: connecting -> connectedIn production, point wsHost at the public load balancer or ingress with forceTls: true, and
create the client in an application-scoped service rather than in a widget’s build method.
Common options
| Option | Type | Default | Description |
|---|---|---|---|
cluster | String | required | Cluster name. Must be non-empty; also used to derive default hosts. |
protocolVersion | int | 7 | 7 is Protocol V1 (Pusher-compatible). Set 2 for Protocol V2. |
forceTls | bool? | null | Anything other than false connects over wss. |
wsHost | String? | null | WebSocket host. Falls back to ws-<cluster>.sockudo.com. |
wsPort / wssPort | int | 80 / 443 | Ports for ws and wss. |
enabledTransports | List<SockudoTransport>? | null | Restrict to SockudoTransport.ws and/or SockudoTransport.wss. |
connectionRecovery | bool | false | Track stream positions and send a V2 resume after reconnect. |
wireFormat | SockudoWireFormat | json | V2 wire format: json, messagepack, or protobuf. |
messageDeduplication | bool | true | Drop repeated message_id values. |
messageDeduplicationCapacity | int | 1000 | Size of the deduplication window. |
activityTimeout | Duration | 120s | V1 idle time before the client sends a ping. |
pongTimeout | Duration | 30s | V1 wait for a pong before reconnecting. |
unavailableTimeout | Duration | 10s | Time in connecting before the state becomes unavailable. |
maxReconnectAttempts | int? | 6 | Reconnect attempts before giving up. null is unlimited. |
maxReconnectGapInSeconds | double | 120.0 | Upper bound on the backoff delay. |
reconnectJitter | double | 0.0 | Fraction of each backoff delay to randomize, clamped to 0–1. |
appendRollupWindow | int? | null | V2 AI append rollup window: 0, 20, 40, 100, or 500. |
Subscribe and bind events
subscribe returns the channel immediately and sends the subscription once the socket is
connected. Bind handlers before or after subscribing; each bind returns an EventBindingToken
you can use to remove exactly that handler later.
final orders = client.subscribe('orders');
orders.bind('sockudo:subscription_succeeded', (_, __) { print('orders is live');});orders.bind('sockudo:subscription_error', (error, _) { print('orders subscription failed: $error');});
final orderToken = orders.bind('order.created', (data, metadata) { print('order: $data from user ${metadata?.userId}');});
// Receive every event on the channel, for logging or reducers.orders.bindGlobal((eventName, data) => print('$eventName $data'));Remove handlers and subscriptions in the owning service or controller’s disposal path:
orders.unbind(eventName: 'order.created', token: orderToken);client.unsubscribe('orders');A connected socket can still have a pending or rejected channel. Wait for the channel’s
subscription-success event before treating its data as live. Client events (client-*) can be
sent with channel.trigger('client-typing', data) on authorized channels.
Private and presence channels
Anyone with your public app key can open a socket, so Sockudo will not let a client join a
private-*, presence-*, or private-encrypted-* channel on its own say-so. Instead, the SDK
asks your backend to sign the subscription. Your backend checks the user’s session, decides
whether that user may join that exact channel, and returns a signature made with the app secret.
Sockudo verifies the signature before admitting the socket.
The default authorizer sends a form-encoded POST with socket_id and channel_name to
channelAuthorization.endpoint (default /sockudo/auth) and expects JSON with auth, plus
channel_data for presence and shared_secret for encrypted channels.
final client = SockudoClient( 'app-key', SockudoOptions( cluster: 'local', forceTls: false, wsHost: '127.0.0.1', wsPort: 6001, protocolVersion: 2, channelAuthorization: ChannelAuthorizationOptions( endpoint: 'https://api.example.com/sockudo/auth', headersProvider: () => <String, String>{ 'Authorization': 'Bearer ${session.accessToken}', }, ), ),);Use an absolute URL for the endpoint; a Flutter app has no page origin to resolve /sockudo/auth
against. To produce the signature yourself, pass customHandler, which receives a
ChannelAuthorizationRequest and returns ChannelAuthorizationData:
ChannelAuthorizationOptions( customHandler: (request) async { final signed = await backend.signChannel(request.socketId, request.channelName); return ChannelAuthorizationData( auth: signed.auth, channelData: signed.channelData, ); },)Presence
Subscribing to a presence-* name returns a PresenceChannel. Its members collection is filled
from the subscription-success payload and kept current as members join, leave, or update.
final presence = client.subscribe('presence-lobby') as PresenceChannel;
presence.bind('sockudo:subscription_succeeded', (_, __) { presence.members.forEach((member) => print('here: ${member.id}')); presence.update(<String, Object?>{'status': 'editing'});});presence.bind('sockudo:member_added', (member, _) => print('joined: $member'));presence.bind('sockudo:member_removed', (member, _) => print('left: $member'));presence.bind('sockudo:presence_update', (member, _) { print((member as PresenceMember).info);});V2 presence updates modify member data without a leave and rejoin cycle. update throws
SockudoException on Protocol V1. Inbound sockudo_internal:presence_update updates
channel.members and emits sockudo:presence_update with the updated PresenceMember.
User sign-in
Configure userAuthentication (default endpoint /sockudo/user-auth, expecting auth and
user_data) and call client.signIn() when the application uses user-targeted events or
watchlists. Bind user events with client.user.on(...) and watchlist events with
client.watchlist.on(...).
Capability tokens
Protocol V2 can authenticate the connection itself with a scoped capability token and an async refresh callback:
final client = SockudoClient( 'app-key', SockudoOptions( cluster: 'local', protocolVersion: 2, wsHost: 'realtime.example.com', forceTls: true, token: initialToken, authCallback: () async => fetchFreshSockudoToken(), ),);
client.bind('sockudo:auth_success', (data, _) => print('token accepted'));tokenis sent as the initial WebSocket query parameter.- When
authCallbackis set and the token is a JWT with anexpclaim, the client decodes it (without validating the signature) and refreshes at 80% of its lifetime. Ifiatis absent, the lifetime starts at the local decode time. Opaque tokens, JWTs withoutexp, and static-onlytokenusage do not schedule proactive refreshes. - After the optional initial token is used,
authCallbacksupplies a fresh token before every reconnect. - On
sockudo:token_expiredwith code40142, the client callsauthCallbackand sendssockudo:authwithout dropping the socket. Revocation code40160cannot refresh in place; it is emitted to listeners and left to the server close path.
Protocol V2 features
Protocol V2 keeps the same channel model but attaches continuity metadata (message_id, serial,
stream_id) to broadcasts and unlocks server-side filtering, deltas, rewind, and mutable messages.
All examples below assume protocolVersion: 2. See Protocol V2 for
the wire-level contract.
Recovery and rewind
With connectionRecovery: true, the client records the latest position for each channel and sends
sockudo:resume after reconnecting. Rewind asks the server to replay recent history at subscribe
time, either by count (SubscriptionRewind.count(n)) or by age (SubscriptionRewind.seconds(n)).
final channel = client.subscribe( 'market:BTC', options: const SubscriptionOptions( rewind: SubscriptionRewind.seconds(30), ),);
channel.bind('sockudo:rewind_complete', (data, _) { final done = data as RewindCompleteData; print('replayed ${done.historicalCount}, complete: ${done.complete}');});
channel.bind('message', (_, __) { print(client.getRecoveryPosition('market:BTC'));});
client.bind('sockudo:resume_success', (data, _) { final result = data as ResumeSuccessData; print('recovered ${result.recovered.length} channels');});
client.bind('sockudo:resume_failed', (data, _) { final failed = data as ResumeFailedChannel; print('rebuild ${failed.channel}: ${failed.code}');});On sockudo:resume_failed, the SDK drops the stored position and resubscribes that channel, but
your derived state may have a gap. Discard it and reload an authoritative snapshot. Persist
positions across process restarts with getRecoveryPositions() and setRecoveryPositions(...).
After a V2 subscription succeeds, channel.attachSerial holds the server’s attach_serial when
durable history is enabled. For a gap-free late join, load channel history with
untilAttach: true, then apply live events:
final room = client.subscribe('presence-room') as PresenceChannel;final history = await room.channelHistory( const ChannelHistoryParams(untilAttach: true, limit: 100),);Filters
Tag filters run on the server, so non-matching messages never reach the device. Build them with the
Filter helpers (eq, neq, inside, notIn, exists, notExists, startsWith, endsWith,
contains, gt, gte, lt, lte, and, or, not). Event-name lists and a bounded JMESPath
expression can be combined with tags; every supplied component must match.
final channel = client.subscribe( 'price:btc', options: SubscriptionOptions( filter: Filter.and(<FilterNode>[ Filter.eq('market', 'spot'), Filter.gt('spread', '0'), ]), events: const <String>['price.updated'], expression: const SubscriptionExpression('data.price >= `100`'), ),);Delta compression
Deltas shrink large, repetitive payloads by sending only the change against the previous message. The SDK reconstructs Fossil and Xdelta3/VCDIFF deltas in pure Dart.
final book = client.subscribe( 'orderbook:btc-usd', options: const SubscriptionOptions( delta: ChannelDeltaSettings( enabled: true, algorithm: DeltaAlgorithm.xdelta3, ), ),);Set deltaCompression: DeltaOptions(...) on SockudoOptions to receive onStats and onError
callbacks, and read totals with client.getDeltaStats(). See
Filters and delta compression.
Mutable messages
Protocol V2 mutable messages arrive as sockudo:message.update, sockudo:message.delete, and
sockudo:message.append. An update replaces local content, a delete is the latest visible version
and may carry null data, and an append concatenates onto the current string. Reduce them in serial
order:
MutableMessageState? state;
final channel = client.subscribe('chat:room-1');channel.bindGlobal((eventName, data) { if (data is! SockudoEvent || !isMutableMessageEvent(data)) return; try { state = reduceMutableMessageEvent(state, data); print('${state?.messageSerial} ${state?.action} ${state?.data}'); } catch (e) { print('mutable message reduction failed: $e'); }});If an append arrives before its base, fetch the latest visible message through the proxy first.
Configure versionedMessages with a trusted backend endpoint to create, append, update, or delete
messages:
final created = await channel.createMessage( const VersionedMessageCreateRequest(data: 'hello'),);await channel.appendMessage(created.messageSerial, ' world');await channel.updateMessage( created.messageSerial, const VersionedMessageMutation(data: <String, Object?>{'text': 'edited'}),);await channel.deleteMessage(created.messageSerial);These helpers send publish_create, message_append, message_update, or message_delete to
versionedMessages.endpoint and resolve to a MessageAck with messageSerial and
historySerial. The default timeout is 10 seconds (VersionedMessagesOptions.timeout). See
Mutable messages.
Presence history
Presence history is proxy-backed. The client does not sign the server REST API; configure
presenceHistory with a backend endpoint that accepts {channel, params, action} and forwards the
request with server credentials.
final client = SockudoClient( 'app-key', SockudoOptions( cluster: 'local', forceTls: false, wsHost: '127.0.0.1', wsPort: 6001, presenceHistory: const PresenceHistoryOptions( endpoint: 'https://api.example.com/sockudo/presence-history', ), ),);
final channel = client.subscribe('presence-lobby') as PresenceChannel;final page = await channel.history( const PresenceHistoryParams(limit: 50, direction: 'newest_first'),);if (page.hasNext()) { final nextPage = await page.next();}
final snapshot = await channel.snapshot( const PresenceSnapshotParams(atSerial: 4),);The history proxy owns the app secret, authenticates the caller, checks channel access, and forwards opaque pagination cursors. See Presence history.
Binary wire formats
Set wireFormat: SockudoWireFormat.messagepack or SockudoWireFormat.protobuf to negotiate a
binary encoding. Both preserve Uint8List message data as native binary. MessagePack uses the
additive ["binary", <bin>] tagged value; existing string and JSON variants are unchanged.
Encrypted channels
private-encrypted-* channels decrypt automatically with libsodium when protected-channel
authorization returns the derived shared_secret (surfaced as ChannelAuthorizationData.sharedSecret):
final encrypted = client.subscribe('private-encrypted-documents');encrypted.bind('doc-updated', (payload, _) => print(payload));Keep the encryption master key on the backend. End-to-end encryption does not replace TLS or channel authorization.
Connection lifecycle and reconnection
The connection moves through ConnectionState values: initialized, connecting, connected,
reconnecting, unavailable, disconnected, and failed. Each change emits state_change with
previous and current names, followed by an event named after the new state. Read the current
value from client.connectionState and the socket ID from client.socketId.
final stateToken = client.bind('state_change', (change, _) { print('connection: ${change['previous']} -> ${change['current']}');});client.bind('connected', (meta, _) => print('socket: ${client.socketId}'));client.bind('reconnecting', (_, __) => print('reconnecting'));
// On sign-out or shutdown:client.unbind(eventName: 'state_change', token: stateToken);client.disconnect();Unexpected disconnects emit ConnectionState.reconnecting and retry with a bounded quadratic delay
of 0s, 1s, 4s, 9s, up to maxReconnectGapInSeconds (120 seconds by default). Protocol retry and
TLS-upgrade close codes reconnect immediately. The default limit is six attempts; null enables
unlimited retries. The attempt counter resets after a successful connection and on explicit
connect() or disconnect() calls. When attempts run out, the state becomes disconnected.
const options = SockudoOptions( cluster: 'local', maxReconnectAttempts: 10, maxReconnectGapInSeconds: 60, reconnectJitter: 0.5,);Let the SDK handle temporary transport failures and resubscription. disconnect() stops
reconnecting and closes the socket; close() also closes the underlying HTTP client used for auth
and proxy requests.
On Protocol V2, Sockudo uses native WebSocket ping/pong frames for heartbeats. Dart runtimes may
still use lightweight sockudo:ping / sockudo:pong fallback messages; those are excluded from
recovery metadata such as message_id, serial, and stream_id.
Error handling
| Failure | How it surfaces | What to do |
|---|---|---|
Invalid construction (empty key or cluster, token on V1, bad appendRollupWindow) | SockudoException thrown by the constructor | Fix configuration. |
| Auth endpoint returns non-200 or invalid JSON | Channel emits subscription_error with type: 'AuthError' and the error text, which includes the HTTP status | Treat 401/403 as a permission problem, not a reconnect loop. |
| Server error frames, decode failures, connection unavailable | Client emits error | Log and observe; the SDK keeps reconnecting where possible. |
Capability token expired (40142) | sockudo:token_expired, then refresh via authCallback | Make sure authCallback can mint a fresh token. |
Capability token revoked (40160) | Emitted to listeners; no in-place refresh, the server closes the connection | Sign the user out or obtain new credentials. |
| Recovery gap | sockudo:resume_failed with ResumeFailedChannel | Discard derived state and reload a snapshot. |
client.bind('error', (error, _) { if (error is SockudoException) { print('sockudo error ${error.statusCode}: ${error.message}'); } else { print('sockudo error: $error'); }});Make handlers idempotent: reconnects, retries, and upstream publishing workflows can repeat logical
work even with message_id deduplication enabled.
Platform notes
Flutter lifecycle
- Scope the client above individual widgets and avoid reconnecting on rebuild.
- Remove bindings and subscriptions when their lifecycle owner is disposed.
- Keep event callbacks fast and move blocking work to an isolate or async service.
- Test background/foreground transitions, offline recovery, token expiry, and application process recreation.
- The package declares a Flutter SDK dependency and opens sockets through
IOWebSocketChannelfromweb_socket_channel.
Large serials on Dart web
On Dart web, serial values that arrive as JSON numbers may already have been rounded by the
JavaScript runtime. The SDK preserves unsafe serials as strings when decoding raw JSON,
MessagePack, Protobuf, and proxy responses where the original literal is still available. Prefer
string serials in app-level web APIs when values may exceed 2^53 - 1.
Push registration
Use a platform push plugin to get the provider token, then send the token to your backend:
final token = await FirebaseMessaging.instance.getToken();
await http.post( Uri.parse('https://api.example.com/sockudo/push/devices'), headers: {'Content-Type': 'application/json'}, body: jsonEncode({ 'device_id': deviceId, 'platform': 'fcm', 'provider_token': token, }),);The backend registers the device with Sockudo and enforces user ownership.
SockudoPushRegistration wraps an authenticated application proxy with typed helpers for device
registrations, channel subscriptions, publishing, scheduling, and status. publish() and
publishBatch() always send sync: false and should expect 202 Accepted with a publish_id;
list helpers use limit and cursor.
final push = SockudoPushRegistration( const PushRegistrationOptions( endpoint: 'https://api.example.com/sockudo/push', headers: <String, String>{'Authorization': 'Bearer session-token'}, ),);
final publish = await push.publish(<String, Object?>{ 'recipients': <Map<String, Object?>>[ <String, Object?>{'type': 'channel', 'channel': 'orders'}, ], 'payload': <String, Object?>{ 'title': 'Order updated', 'body': 'Ready for pickup', },});print(publish['publish_id']);Apple Live Activities
ActivityKit runs in the iOS host and Widget Extension because its APIs use the application’s custom
ActivityAttributes. sockudo_flutter therefore integrates with any native bridge instead of
forcing one plugin version. A current option is the
live_activities Flutter plugin, which exposes activity
token and push-to-start token streams. Upload every rotation to your authenticated backend, and
keep listening for the activity’s entire lifetime because Apple can rotate tokens at any time:
liveActivities.pushToStartTokenUpdateStream.listen((token) async { await backend.replaceLiveActivityToken( ApnsLiveActivityTokenUpdate.pushToStart(token).toJson(), );});
final update = ApnsLiveActivityTokenUpdate.activity( activityId: activityId, token: activityToken,);await backend.replaceLiveActivityToken(update.toJson());For an application proxy that authorizes the current user and activity, construct a validated direct
or broadcast request with ApnsLiveActivityPublishRequest, ApnsLiveActivityPayload, and either
ApnsLiveActivityTokenRecipient or ApnsLiveActivityBroadcastRecipient, then send it with
push.publishLiveActivity(...). The helper rejects invalid start fields, direct priority
lowPower, and broadcast start requests before network I/O.
await push.publishLiveActivity( ApnsLiveActivityPublishRequest( publishId: 'ride-184-update-42', recipient: const ApnsLiveActivityTokenRecipient(currentActivityToken), liveActivity: const ApnsLiveActivityPayload( event: ApnsLiveActivityEvent.update, timestamp: 1725000042, contentState: <String, Object?>{'status': 'arriving', 'etaMinutes': 1}, priority: ApnsLiveActivityPriority.conservePower, ), ),);See Apple Live Activities for channel setup, broadcast delivery, and the complete payload contract.