# How to Build a Social Media Aggregator in FlutterFlow

- Tool: FlutterFlow
- Difficulty: Beginner
- Time required: 30-40 min
- Compatibility: FlutterFlow Free+
- Last updated: March 2026

## TL;DR

Build a social media aggregator that connects to Twitter, Instagram, and YouTube APIs via Cloud Functions, normalizes posts into a unified social_posts Firestore collection, and displays them in a single feed. Each post card shows the platform badge, content preview, engagement count, and a link to the original. Users connect accounts through OAuth flows and can view cross-platform engagement analytics.

## Building a Unified Social Feed from Multiple Platforms

Managing multiple social media accounts means switching between apps constantly. This tutorial builds a single aggregated feed that pulls your posts from Twitter/X, Instagram, and YouTube into one view. Connect accounts via OAuth, fetch posts through Cloud Functions, and display everything in a unified timeline with engagement analytics.

## Before you start

- A FlutterFlow project with Firestore and authentication configured
- API credentials for at least one social platform (Twitter API, Instagram Basic Display API, or YouTube Data API)
- Cloud Functions environment set up for your project
- Basic understanding of REST API calls and OAuth flows

## Step-by-step guide

### 1. Design the Firestore data model for aggregated social posts

Create a social_posts collection with fields: userId (String), platform (String: 'twitter', 'instagram', 'youtube'), platformPostId (String, the original post ID), content (String, text or caption), mediaUrl (String, nullable), mediaType (String: 'image', 'video', 'text'), timestamp (Timestamp), engagementCount (Integer, likes + comments combined), postUrl (String, link to original post). Also create a connected_accounts collection with: userId, platform, accessToken (encrypted), refreshToken, tokenExpiry, platformUsername. This normalized schema lets you query all platforms in one feed.

**Expected result:** Firestore has social_posts for unified content and connected_accounts for OAuth token storage per platform.

### 2. Build Cloud Functions for OAuth account connection

Create three Cloud Functions for connecting social accounts. Each function initiates the OAuth flow: generate an auth URL with required scopes, redirect the user, and handle the callback to exchange the authorization code for access and refresh tokens. Store tokens in connected_accounts with the platform field. For Twitter use OAuth 2.0 PKCE, for Instagram use Instagram Basic Display API OAuth, for YouTube use Google OAuth with youtube.readonly scope. Encrypt access tokens before storing in Firestore using a server-side encryption key.

```
// Cloud Function: connectTwitter (simplified)
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const crypto = require('crypto');

const ENCRYPT_KEY = process.env.TOKEN_ENCRYPT_KEY;

function encrypt(text) {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv(
    'aes-256-cbc', Buffer.from(ENCRYPT_KEY), iv
  );
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return iv.toString('hex') + ':' + encrypted;
}

exports.handleTwitterCallback = functions.https
  .onRequest(async (req, res) => {
    const { code, state } = req.query;
    const userId = state; // passed during auth init
    // Exchange code for tokens
    const tokenRes = await fetch(
      'https://api.twitter.com/2/oauth2/token',
      { method: 'POST', body: new URLSearchParams({
        grant_type: 'authorization_code',
        code, redirect_uri: REDIRECT_URI,
        client_id: CLIENT_ID,
        code_verifier: STORED_VERIFIER
      })}
    );
    const tokens = await tokenRes.json();
    await admin.firestore()
      .collection('connected_accounts').add({
        userId, platform: 'twitter',
        accessToken: encrypt(tokens.access_token),
        refreshToken: encrypt(tokens.refresh_token),
        tokenExpiry: Date.now() + tokens.expires_in * 1000,
        platformUsername: tokens.screen_name
      });
    res.redirect('/account-connected?platform=twitter');
  });
```

**Expected result:** Users can connect their Twitter, Instagram, and YouTube accounts via OAuth, with tokens stored encrypted in Firestore.

### 3. Create a Cloud Function to fetch and normalize posts from all platforms

Build a scheduled Cloud Function (runs every hour) that iterates through connected_accounts, decrypts tokens, calls each platform API to fetch recent posts, and normalizes them into social_posts documents. For Twitter: GET /2/users/:id/tweets. For Instagram: GET /me/media. For YouTube: GET /youtube/v3/search?forMine=true. Map each response to the unified schema: extract content text, media URL, engagement metrics, and original post URL. Use platformPostId to avoid duplicate entries on subsequent fetches.

**Expected result:** Cloud Function periodically fetches posts from all connected platforms and writes normalized documents to social_posts.

### 4. Build the unified feed page with platform badges

Create an AggregatedFeedPage. Add a TabBar at the top with tabs: All, Twitter, Instagram, YouTube. Below, add a ListView with a Backend Query on social_posts filtered by userId equals current user, ordered by timestamp descending. For the 'All' tab, show all platforms. For individual tabs, add a where clause on platform. Each list item is a PostCard Container: a Row with a platform badge icon (bird for Twitter, camera for Instagram, play button for YouTube) using conditional Image based on the platform field, followed by a Column with content Text (truncated to 2 lines), mediaUrl as Image if present, engagementCount with a heart icon, and timestamp as relative time.

**Expected result:** A unified feed displays posts from all connected platforms with filterable tabs and platform-specific badges.

### 5. Add engagement analytics with cross-platform comparison

Create an AnalyticsPage accessible from a chart icon in the AppBar. Query social_posts grouped by platform and sum engagementCount. Display a Custom Widget bar chart (using fl_chart) comparing total engagement across platforms. Below the chart, show stat cards: total posts per platform, average engagement per post, most engaging post with a link. Add a date range picker to filter analytics to specific periods. This helps users understand which platform drives the most engagement.

**Expected result:** An analytics page shows bar charts comparing engagement across Twitter, Instagram, and YouTube with summary statistics.

### 6. Implement the cross-posting feature to publish to multiple platforms

Add a ComposePostPage with a TextField for content, an optional image picker, and ChoiceChips for selecting target platforms (Twitter, Instagram, YouTube). On submit, call a Cloud Function that receives the content and selected platforms, decrypts each platform's tokens, and posts via their respective APIs. Twitter: POST /2/tweets. Instagram: requires Facebook Graph API media creation flow. YouTube: community posts or video descriptions. Show a success/failure status per platform in a results dialog after posting.

**Expected result:** Users compose a post once and publish it to all selected social media platforms simultaneously.

## Complete code example

File: `FlutterFlow Social Aggregator Setup`

```text
FIRESTORE DATA MODEL:
  social_posts/{postId}
    userId: String
    platform: 'twitter' | 'instagram' | 'youtube'
    platformPostId: String (dedup key)
    content: String
    mediaUrl: String (nullable)
    mediaType: 'image' | 'video' | 'text'
    timestamp: Timestamp
    engagementCount: Integer
    postUrl: String (link to original)

  connected_accounts/{accountId}
    userId: String
    platform: String
    accessToken: String (encrypted)
    refreshToken: String (encrypted)
    tokenExpiry: Integer
    platformUsername: String

PAGE: AggregatedFeedPage
  WIDGET TREE:
    Column
      ├── TabBar (All | Twitter | Instagram | YouTube)
      └── Expanded
            └── ListView
                  Backend Query: social_posts
                    where userId == currentUser.uid
                    where platform == selectedTab (if not All)
                    order by timestamp desc
                  Generate Dynamic Children → PostCard

  PostCard Container:
    Row
      ├── Image (platform badge: conditional on platform field)
      └── Column
            ├── Text (content, maxLines: 2)
            ├── Image (mediaUrl, if not null)
            ├── Row
            │     ├── Icon (heart) + Text (engagementCount)
            │     └── Text (relative timestamp)
            └── InkWell → Launch URL (postUrl)

PAGE: AnalyticsPage
  WIDGET TREE:
    Column
      ├── DateRangePicker
      ├── Custom Widget (fl_chart bar chart: engagement by platform)
      └── Row (stat cards: posts count, avg engagement per platform)

CLOUD FUNCTIONS:
  1. connectTwitter / connectInstagram / connectYouTube (OAuth)
  2. fetchSocialPosts (scheduled hourly, fetches + normalizes)
  3. crossPost (posts content to selected platforms)
```

## Common mistakes

- **Storing social platform access tokens unencrypted in Firestore** — If the database is compromised, an attacker gains full control of users' social media accounts. This is a critical security vulnerability. Fix: Encrypt tokens with a server-side key before storing. Decrypt only inside Cloud Functions when making API calls. Never expose tokens to the client.
- **Fetching posts from APIs on every page load instead of caching** — Social media APIs have strict rate limits (Twitter: 100 requests per 15 minutes). Hitting limits blocks all users and shows errors. Fix: Use a scheduled Cloud Function to fetch posts periodically (every hour) and store them in Firestore. The client reads cached data from Firestore.
- **Not handling expired OAuth tokens with automatic refresh** — Access tokens expire (Twitter: 2 hours, Instagram: 60 days). Without refresh logic, the feed silently stops updating and users see stale content. Fix: Check token expiry before each API call in the Cloud Function. If expired, use the refresh token to get a new access token and update Firestore.

## Best practices

- Encrypt all OAuth tokens before storing in Firestore and decrypt only in Cloud Functions
- Use a scheduled Cloud Function to fetch posts periodically rather than on every page load
- Deduplicate posts using platformPostId to prevent duplicates on repeated fetches
- Implement automatic token refresh logic to handle expired access tokens silently
- Normalize all platform data into a single schema for consistent UI rendering
- Show platform badges on each post so users can quickly identify the source
- Add rate limit handling with exponential backoff in Cloud Functions

## Frequently asked questions

### Which social media APIs are free to use?

YouTube Data API offers 10,000 quota units per day free. Instagram Basic Display API is free with rate limits. Twitter API free tier allows 1,500 tweets per month for reading. For higher volumes, paid tiers are required.

### Can I add more platforms like TikTok or LinkedIn?

Yes. Add a new Cloud Function for OAuth connection, implement the fetch logic for that platform's API, and normalize the response into the same social_posts schema. The unified feed displays it automatically.

### How do I handle rate limits from social media APIs?

Implement exponential backoff in Cloud Functions. If an API returns a 429 rate limit error, wait and retry with increasing delays. Also spread fetches across users to avoid hitting limits for all accounts simultaneously.

### Is it safe to store OAuth tokens in Firestore?

Only if encrypted with a server-side key. Never store plain-text tokens. Decrypt only inside Cloud Functions when making API calls. Also implement Firestore Security Rules so only the Cloud Function service account can read connected_accounts.

### Can users disconnect a social account?

Yes. Add a Disconnect button per platform that deletes the connected_accounts document and optionally deletes cached social_posts for that platform. Also revoke the OAuth token via the platform's revoke endpoint.

### Can RapidDev help build a social media aggregator with advanced features?

Yes. RapidDev can implement multi-platform OAuth, automated content fetching, sentiment analysis, scheduling tools, and detailed engagement dashboards tailored to your specific needs.

---

Source: https://www.rapidevelopers.com/flutterflow-tutorials/how-to-build-a-social-media-aggregator-in-flutterflow
© RapidDev — https://www.rapidevelopers.com/flutterflow-tutorials/how-to-build-a-social-media-aggregator-in-flutterflow
