Photo Social App with FlutterFlow and Supabase · Course book
Chapter 32: Real-Time Chat
The chat built earlier works, but it has one obvious gap: a new message only appears after the other person refreshes. Real messaging apps show messages the instant they are sent. This chapter closes that gap with Supabase Realtime, which pushes new rows to the app as they are inserted. It explains how Realtime works compared with refreshing, creates the custom actions that subscribe to and unsubscribe from a conversation, connects them to the chat page in FlutterFlow, configures Supabase so the messages table broadcasts its changes, considers the usage and pricing limits that real-time features carry, and tests and fixes the common errors. The cost of the two approaches is worked out by hand with a graph.
Push instead of pull
Without Realtime, the app has to pull: ask the database for new messages, either when the user refreshes or automatically every few seconds, a technique called polling. Polling is simple but wasteful, because most requests return nothing new, and slow, because a message waits on average half the polling interval before the next check finds it.
Realtime lets the database push instead. The app opens one long-lived connection, a WebSocket, to Supabase and subscribes to a channel describing what it wants to hear about, such as "inserts into the messages table where the chat id is 42". When a matching row is inserted, Supabase sends it down the connection immediately, and the app adds it to the conversation. Nothing travels when nothing happens.
Supabase Realtime offers three kinds of channel feature, each suited to a different job. Postgres changes, used in this chapter, broadcast inserts, updates and deletes on chosen tables, which suits anything stored in the database, such as messages, likes or new comments. Broadcast sends short messages between connected clients without storing them, which suits fleeting signals such as "Maya is typing…", where saving a row for every keystroke would be wasteful. Presence tracks who is currently connected to a channel, which powers green "online now" dots on a chat list. A full-featured chat often uses all three: changes for messages, broadcast for typing indicators and presence for online status.
Pushed updates complement queries rather than replacing them. When the chat page opens, an ordinary query still loads the recent history, because a subscription only reports changes that happen after it starts. The subscription then keeps the page current from that moment on. Thinking of it as "load once, then listen" makes the whole design clear and easy to reason about.
Custom actions for subscribing
FlutterFlow's built-in queries fetch data when asked, so listening for changes is handled with custom actions that use the Supabase client's Realtime features directly. Two are needed.
RealtimeChannel? chatChannel;
Future subscribeToChat(int chatId, Future Function() onNewMessage) async {
chatChannel = Supabase.instance.client
.channel('chat-$chatId')
.onPostgresChanges(
event: PostgresChangeEvent.insert,
schema: 'public',
table: 'messages',
filter: PostgresChangeFilter(
type: PostgresChangeFilterType.eq, column: 'chat_id', value: chatId),
callback: (payload) => onNewMessage(),
)
.subscribe();
}
Future unsubscribeFromChat() async {
if (chatChannel != null) {
await Supabase.instance.client.removeChannel(chatChannel!);
chatChannel = null;
}
}
The first action opens a channel named after the chat and listens for inserts into messages filtered to that chat's id. When one arrives, it runs a callback that the page supplies, typically an action that refreshes the message list, or adds the new message from the payload directly. The second action removes the channel. Exact method names can differ between versions of the Supabase Dart library, so check the version your FlutterFlow project uses. Keeping the channel in a variable that both actions can see is what lets the second action remove exactly the channel the first one created.
Wiring it into the chat page
On the chat page, the subscribe action runs when the page loads, given the page's chat id and a callback that refreshes the message query. The unsubscribe action runs when the page is closed, so that the app does not keep listening to a conversation nobody is viewing; leaving subscriptions open wastes connections and can cause duplicate updates when the page is opened again. With both in place, a message sent from one phone appears on the other within moments, and the list stays at the newest message without the user lifting a finger.
The sender's own message also arrives through the subscription, so the page must avoid showing it twice. The simplest approach lets the subscription's refresh display all messages, including the user's own; if the page also adds messages optimistically on sending, it should replace the temporary entry when the real row arrives rather than adding a second copy. The chat groups page can use the same technique on the chats table, so previews and ordering update live too.
Refreshing the whole list on every new message is the simplest callback, and for short conversations it is perfectly adequate. For long or busy chats, using the message carried in the payload is more efficient: the callback appends that single row to the list held in page state, without fetching anything. The payload contains the row's columns, such as the content, the sender's id and the time, so the bubble can be drawn immediately, with the sender's name looked up from the chat's member list already loaded. Either way, the list should stay scrolled to the newest message when the user is at the bottom, but should not jump if they have scrolled up to read older messages; a small "New message" button can then take them down when they are ready.
Configuring Supabase and understanding the costs
Realtime is not switched on for every table by default. In the Supabase dashboard, the messages table must be added to the Realtime publication, the list of tables whose changes are broadcast. Row level security still applies: a subscriber receives only rows they are allowed to read, so the membership policy on messages ensures nobody hears another conversation, even by subscribing directly to its id.
Realtime has limits and costs that matter as an app grows. Supabase plans include quotas for the number of concurrent connections and the number of messages delivered, with higher usage on paid plans. Each person with the app open and subscribed holds a connection, and each delivered change counts as a message. The current figures are on Supabase's pricing and usage pages and change over time, so check them for your plan. Design habits keep usage low: subscribe only on screens that need live data, filter channels narrowly to one chat rather than the whole table, and unsubscribe when screens close. Watching the Realtime usage figures in the Supabase dashboard during testing, and again after launch, shows whether these habits are working, long before any limit is reached.
| Habit | Effect on usage |
|---|---|
| Subscribe on the chat page only | Connections only for people actively chatting |
| Filter by chat id | Each person receives only their conversation's messages |
| Unsubscribe when the page closes | No idle channels or duplicate deliveries |
| Refetch on reconnect | Fills gaps without polling continuously |
Testing and fixing errors
Real-time features must be tested on two devices at once: open the same conversation on both, send from each, and confirm the message appears on the other within a second or two. Then close and reopen the chat several times and check that messages never appear twice, which would indicate subscriptions not being removed. Put one phone in airplane mode, send messages from the other, reconnect, and check that the missed messages appear; since a disconnected phone hears nothing, the page should refetch when the connection returns or the app comes back to the foreground. If nothing arrives at all, the usual causes are the table missing from the Realtime publication, a filter on the wrong column, or a read policy that blocks the subscriber. With live chat working, the photo app's messaging feels like the real thing, and the series' app is complete.
Practice tasks
- With 500 people polling every 5 seconds, how many requests per hour does the app receive?
- Those 500 people send 3,000 one-to-one messages an hour. How many messages does Realtime deliver?
- Why must the unsubscribe action run when the chat page closes?
- Explain how row level security keeps Realtime subscriptions private.
- A message appears twice after the page is reopened. What is the likely cause?
- Describe how the chat page should recover messages sent while a phone was offline.
This course book is available to read online only at tech-academy.chrysolites.org.