Building Real-time Chat in Flutter: Strategies for User-to-User and AI Streaming
The Flutter news you actually need
No spam, ever. Unsubscribe in one click.
In-app chat has become a standard feature, but its implementation has split into two distinct paradigms: the classic user-to-user conversation and the new frontier of streaming AI/LLM responses. Each presents unique architectural puzzles, from syncing unread counts across devices to handling a continuous, real-time stream of tokens from an AI model. Let’s break down robust strategies for both in Flutter.
The Core Distinction: Stateful vs. Streaming
First, understand the fundamental difference. Traditional chat is about synchronizing state. A message is a discrete piece of data (sender, text, timestamp) that must be consistently available to all participants. AI chat, however, is often about streaming an event. You send a prompt, and you receive a long, real-time trickle of text that forms the final response.
Mixing the logic for these two patterns is a common mistake that leads to messy, hard-to-maintain code. Treat them as separate concerns in your architecture.
Strategy 1: User-to-User Chat (Synchronizing State)
For human conversations, you need a reliable, centralized source of truth. Client-side counters for unread messages are a notorious trap—if a user reads a message on their phone, the counter on their tablet must update instantly.
Solution: Centralize Read Status
The key is to store the last read timestamp per user per chat in your backend database, not a count on the client. Here’s a simplified model:
// Example data models
class ChatMessage {
final String id;
final String chatId;
final String senderId;
final String text;
final DateTime timestamp;
ChatMessage({
required this.id,
required this.chatId,
required this.senderId,
required this.text,
required this.timestamp,
});
}
class ChatMember {
final String userId;
final String chatId;
DateTime lastReadAt; // This is the critical field
// ...
}
Your Flutter app listens to new messages and compares their timestamps to the user’s lastReadAt for that chat.
StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
stream: firestore
.collection('chats/$chatId/messages')
.orderBy('timestamp', descending: true)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return CircularProgressIndicator();
final messages = snapshot.data!.docs
.map((doc) => ChatMessage.fromFirestore(doc))
.toList();
final lastRead = currentUserLastReadTimestamp; // Fetched from a separate listener
return ListView.builder(
reverse: true,
itemCount: messages.length,
itemBuilder: (ctx, index) {
final message = messages[index];
final isUnread = message.timestamp.isAfter(lastRead);
return MessageBubble(
message: message,
isUnread: isUnread,
);
},
);
},
)
When the user opens the chat, your app updates the backend’s ChatMember.lastReadAt field. All other devices subscribed to this user’s data via a real-time listener (Firestore snapshots, Supabase Realtime, or a WebSocket) will receive the update and recalculate unread states instantly.
Typing Indicators are transient state. Don’t store them in your main messages collection. Use a dedicated, low-cost real-time channel (like Firebase Realtime Database, a Supabase Realtime channel, or a specific WebSocket message) that broadcasts and cleans up these ephemeral events.
Strategy 2: AI Response Streaming (Handling Events)
AI streaming is a one-to-one flow. You make a request, and you open a pipe for the response. Server-Sent Events (SSE) are perfectly suited for this and often simpler than bidirectional WebSockets for this unidirectional stream.
Common Mistake: Trying to shove streaming tokens into the same Firestore document as your chat history. This creates huge overhead and cost.
Solution: Use a Dedicated Stream Endpoint
Here’s a practical approach using the http and sse_client packages for a clean stream:
- Backend: Set up an endpoint (e.g.,
/api/chat/completions) that returns antext/event-streamresponse. - Flutter: Connect to the stream and listen for tokens.
import 'package:sse_client/sse_client.dart';
import 'dart:async';
class AIChatService {
final SseClient _client;
AIChatService(String baseUrl) : _client = SseClient(Uri.parse('$baseUrl/api/chat/completions'));
Stream<String> streamCompletion(String prompt) async* {
// Send the initial prompt via the connection URI or a POST request
// Implementation depends on your backend API
// _client.sink.add('prompt: $prompt'); // This line is speculative
await for (var event in _client.stream) {
// Assume your server sends events with data: "token"
if (event.data != null) {
yield event.data!;
}
}
}
void dispose() {
_client.close();
}
}
// Usage in your UI
String _accumulatedResponse = '';
Future<void> _sendPrompt(String prompt) async {
final service = AIChatService('https://your-backend.com');
await for (final token in service.streamCompletion(prompt)) {
// This callback fires for every token
setState(() {
_accumulatedResponse += token;
});
}
// Once the stream ends, you can now save the complete
// `_accumulatedResponse` as a single message to your
// main chat history database (e.g., Firestore).
}
This keeps your streaming logic isolated. The final, complete response can then be saved as a regular ChatMessage in your primary database for history and sync, giving you the best of both worlds.
Architectural Recommendation
- For User Chat: Use a managed real-time database (Firestore, Supabase) or a dedicated WebSocket backend for state synchronization. Centralize all critical state like
lastReadAton the server. - For AI Streaming: Implement a separate service using SSE or WebSockets. Keep the streaming channel purely for the live token delivery. Persist the final result into your main chat system only after the stream is complete.
By separating these two patterns conceptually and in your codebase, you build a system that is scalable, maintainable, and provides a smooth real-time experience for both human conversation and AI interaction.
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.