Mastering Flutter AI Chat: Handling Streaming Protocols and Reconnections with Vercel AI SDK
The Flutter news you actually need
No spam, ever. Unsubscribe in one click.
Integrating AI chat into Flutter usually starts with a simple fetch call and a Text widget. It breaks when the model streams: tokens arrive in arbitrary chunks, tool calls split across events, and a dropped connection can leave the UI half-finished. The fix is to treat the stream as a stateful protocol, not a sequence of strings.
Parse the stream as events
Most Vercel AI SDK stream transports send newline-delimited JSON or SSE data: lines. Never assume one network chunk equals one complete event. Buffer until a newline appears.
import 'dart:convert';
class ChatEvent {
final String type;
final Map<String, dynamic> payload;
ChatEvent(this.type, this.payload);
}
class ChatStreamDecoder {
String _pending = '';
Stream<ChatEvent> decode(Stream<List<int>> bytes) async* {
await for (final chunk in bytes.transform(utf8.decoder)) {
_pending += chunk;
while (_pending.contains('\n')) {
final nl = _pending.indexOf('\n');
var line = _pending.substring(0, nl).trim();
_pending = _pending.substring(nl + 1);
if (line.startsWith('data:')) line = line.substring(5).trim();
if (!line.startsWith('{')) continue;
try {
final json = jsonDecode(line) as Map<String, dynamic>;
yield ChatEvent('${json['type'] ?? 'unknown'}', json);
} catch (_) {
// Log this in production. Malformed lines are usually transport issues.
}
}
}
var line = _pending.trim();
_pending = '';
if (line.startsWith('data:')) line = line.substring(5).trim();
if (line.startsWith('{')) {
try {
final json = jsonDecode(line) as Map<String, dynamic>;
yield ChatEvent('${json['type'] ?? 'unknown'}', json);
} catch (_) {}
}
}
}
This decoder tolerates partial chunks and flushes the final line if the server does not end with a newline. In production, log malformed lines instead of swallowing them silently.
Handle tool calls incrementally
Tool calls are where naive parsers fail. A call may arrive as a start event, then several argument deltas, then a result. Accumulate by tool ID.
class ToolCallState {
final String id;
final String name;
final StringBuffer args = StringBuffer();
ToolCallState(this.id, this.name);
}
void apply(
ChatEvent event,
Map<String, ToolCallState> tools,
Map<String, StringBuffer> textByMessage,
) {
switch (event.type) {
case 'text-delta':
final id = event.payload['messageId'] as String;
textByMessage
.putIfAbsent(id, () => StringBuffer())
.write(event.payload['delta'] ?? '');
break;
case 'tool-call':
final id = event.payload['toolCallId'] as String;
tools[id] = ToolCallState(id, event.payload['toolName'] as String);
break;
case 'tool-args-delta':
final id = event.payload['toolCallId'] as String;
tools[id]?.args.write(event.payload['delta'] ?? '');
break;
}
}
Use the accumulated args string only when the call is complete. If your UI shows tool progress, render it as a pending card rather than raw JSON. In a Flutter screen, keep these maps in a ValueNotifier or state object and rebuild a ListView from the latest message IDs.
Reconnect with a cursor and deduplication
The hard part is resilience. If the socket dies mid-response, resume from the last processed event instead of re-requesting the whole message. Use a cursor, and deduplicate by a stable event ID.
import 'package:http/http.dart' as http;
class ResilientChatClient {
final Uri endpoint;
final Set<String> _seen = {};
String? _cursor;
Stream<ChatEvent> stream() async* {
while (true) {
final request = http.Request('GET', endpoint)
..headers['X-Cursor'] = _cursor ?? '';
try {
final response = await request.send();
if (response.statusCode != 200) throw Exception('Bad response');
await for (final event in ChatStreamDecoder().decode(response.stream)) {
final id = event.payload['eventId']?.toString() ??
'${event.payload['messageId']}:${event.payload['sequence']}';
if (_seen.add(id)) {
_cursor = id;
yield event;
}
}
return;
} on Exception {
await Future.delayed(const Duration(seconds: 2));
}
}
}
}
The server must honor the cursor for true resumption. If it cannot, the dedupe set still prevents duplicate UI updates, but you may refetch more data than necessary. For long sessions, prune _seen by completed message IDs and add jitter to reconnect delays.
Common mistakes to avoid
- Using
http.getand waiting for the full body. Userequest.send()and streamresponse.stream. - Appending every
text-deltato the last visible message. UsemessageId. - Retrying without dedupe. Resumed streams can replay events.
- Treating
finishas the end of the entire workflow. It may only end the assistant turn; tool follow-ups can continue.
Once the parser owns buffering, the UI owns state, and the transport owns recovery, AI chat in Flutter becomes much less mysterious.
This blog is produced with the assistance of AI by a human editor. Learn more
Related Posts
Fixing Flutter TextField Issues: Preventing Input Lag, Lost Keystrokes, and Keyboard Glitches
Many Flutter developers struggle with common TextField issues like typing lag, lost keystrokes, or erratic keyboard behavior. This post will diagnose the root causes of these problems, including state management, TextEditingController misuse, and custom decorations, offering practical solutions for a smooth and reliable user input experience.
Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data
Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.
Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring
Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.