Photo Social App with FlutterFlow and Supabase · Course book
Chapter 24: Unfollowing and Count Triggers
Following is only half of the relationship; people also need to unfollow, and the app must handle it as reliably as following. Unfollowing removes a row from the follow table, but it also has to lower two counts, update every screen that shows the follow state, and leave no trace of the old relationship. This chapter builds the unfollow function in FlutterFlow, extends the Supabase trigger so the counts fall as well as rise, explains how to keep stored counts trustworthy over thousands of follows and unfollows, worked through by hand with a graph, and tests the complete follow system with two accounts.
The unfollow function
On another user's profile, when the viewer already follows them, the button shows "Following". Tapping it unfollows, usually after a quick confirmation, because unfollowing by accident is irritating and the other person may notice. Many apps show a small sheet with the person's picture and a clear "Unfollow" option rather than acting on the first tap.
The action is a Delete Row on user_follower, filtered to the row where follower_id is the signed-in user and following_id is the profile's owner. Because of the unique constraint on that pair, the filter matches at most one row, so the delete can never remove anything else by mistake. The row level security policy for deletes allows users to delete only rows where they are the follower, so nobody can make another person unfollow someone.
After the delete succeeds, the app removes the profile owner's id from the list of followed ids in app state, so the button changes back to "Follow" and every other screen that checks the list, such as a following feed or suggestion list, updates at once. If the delete fails, the button returns to "Following" and a short message explains, so the screen never shows a state the database does not have.
The visible follower count on the profile should also respond instantly. Just as following added one to the displayed number before the refresh, unfollowing subtracts one, using the change in the followed list to know which adjustment to make. When the profile is next loaded, the stored count, updated by the trigger, replaces the adjusted figure. Doing both, the instant local change and the authoritative stored value, gives the speed of an optimistic interface with the correctness of the database.
Unfollowing has consequences elsewhere in the app that are worth listing. If the app shows a following feed, the person's posts should disappear from it on the next refresh. If chat is limited to mutual followers, unfollowing may end the ability to message, while earlier messages remain readable. And any notification that "Maya started following you" becomes out of date; most apps simply leave old notifications as a record of what happened rather than deleting them. Deciding these behaviours deliberately avoids surprises for users.
| Event | Row in user_follower | Follower's following_count | Followed user's follower_count |
|---|---|---|---|
| Follow | Inserted | +1 | +1 |
| Unfollow | Deleted | −1 | −1 |
| Repeated follow (duplicate) | Rejected by the unique constraint | No change | No change |
| Unfollow when not following | Nothing to delete | No change | No change |
| Account deleted | All its rows deleted by cascade | −1 for each person it followed | −1 for each person who followed it |
The unfollow trigger
The previous part's trigger raised two counts when a follow was inserted. Unfollowing needs the mirror image: when a row is deleted, lower the follower's following_count and the followed user's follower_count by one each. The cleanest approach is one trigger function that handles both events, checking which operation fired it, like the like-count trigger did.
create or replace function public.update_follow_counts()
returns trigger language plpgsql security definer set search_path = public as $$
begin
if tg_op = 'INSERT' then
update users set following_count = following_count + 1 where id = new.follower_id;
update users set follower_count = follower_count + 1 where id = new.following_id;
return new;
elsif tg_op = 'DELETE' then
update users set following_count = greatest(following_count - 1, 0) where id = old.follower_id;
update users set follower_count = greatest(follower_count - 1, 0) where id = old.following_id;
return old;
end if;
return null;
end; $$;
create trigger on_follow_change
after insert or delete on public.user_follower
for each row execute function public.update_follow_counts();
For deletes, the function reads the removed row from OLD, since there is no new row. The greatest(…, 0) guard keeps counts from going negative if anything ever goes out of step. Because the trigger fires for every row, a cascade that deletes many follows when an account is removed lowers every affected count correctly, one row at a time, with no extra work in the app.
If the earlier trigger fired only on insert, it must be replaced or a second trigger added for delete; having two triggers that both handle inserts would add two for every follow, a classic mistake. Listing the triggers on the table in the Supabase dashboard confirms exactly what is attached.
Testing the trigger in the SQL editor before using the app is quick and conclusive. Insert a follow row by hand and check that both users' counts rose; delete it and check that both fell back to where they started; delete a row that does not exist and check that nothing changed. Because a failing trigger function makes the delete itself fail, any mistake in the function shows up immediately as an error message naming the problem, such as a misspelt column, which is easier to fix there than through the app's interface.
Keeping counts trustworthy
A stored count is a copy of information that also exists as rows, so it must stay equal to the true number. The trigger keeps it equal for every change made after it was created, as long as every follow and unfollow passes through the table. A sequence of events shows how the count tracks reality.
Counts can still drift for reasons outside the trigger: rows inserted before it existed, a trigger briefly disabled during maintenance, or a bulk import. A reconciliation query fixes any drift by setting every user's two counts to the true number of matching rows. Running it once after creating the trigger, and occasionally afterwards as a check, keeps the numbers honest; if it ever changes a value, that is a sign to investigate what bypassed the trigger.
The reconciliation itself is a single update that, for each user, counts the follow rows in which they are the followed person and stores that number, and does the same for the rows in which they are the follower. On a large table it reads every follow row once, which is far more work than the trigger's one-row updates, so it belongs in an occasional maintenance task, perhaps scheduled weekly, rather than in the app. Supabase supports scheduled jobs for exactly this kind of periodic database work.
Testing the follow system
With both directions working, the follow system deserves a full test with two accounts. Follow from account A and check that A's following count and B's follower count rise. Unfollow and check that both fall back. Follow, unfollow and follow again quickly, then confirm there is exactly one row and the counts match it. Delete a test account that follows and is followed by others, then confirm every related count drops and no orphaned rows remain. Finally, run the reconciliation query and check that it changes nothing, which proves the trigger has kept everything in step.
On the interface side, check that the button changes immediately on tap, shows the confirmation before unfollowing, and is correct after restarting the app, and that the follower and following lists, if built, update after a change. With following complete, the next part builds out the profile pages and the edit profile feature, where these counts are displayed.
Practice tasks
- A user starts with 12 followers. Over a week, 9 people follow and 4 unfollow. What is the final count, and how many rows should the table hold for them?
- Write the filters for the Delete Row action that unfollows the profile's owner.
- Why does the delete branch of the trigger use
OLDrather thanNEW? - What goes wrong if two separate triggers both increment counts on insert?
- Describe in words the reconciliation query that recalculates every user's follower count.
- List four tests that together show the follow system is correct.
This course book is available to read online only at tech-academy.chrysolites.org.