# How to Build a Behavior-Based Product Recommendation System in FlutterFlow

- Tool: FlutterFlow
- Difficulty: Beginner
- Time required: 30-40 min
- Compatibility: FlutterFlow Pro+ (Cloud Functions for recommendation engine)
- Last updated: March 2026

## TL;DR

Build product recommendations by tracking user events (views, cart adds, purchases) in Firestore. A Cloud Function runs collaborative filtering: finds co-viewed and co-purchased products, scores them, and writes the top 10 to each user's recommendations subcollection. Display a Recommended for You carousel on the home page and a Customers Also Bought section on product pages. Each recommendation includes a reason string explaining the suggestion.

## Building a Behavior-Based Recommendation Engine in FlutterFlow

Product recommendations drive 35% of Amazon's revenue. This tutorial builds a recommendation engine for your FlutterFlow e-commerce app by tracking what users view, add to cart, and buy, then using collaborative filtering in Cloud Functions to suggest products they are likely to want. Recommendations are pre-computed and stored in Firestore for instant display.

## Before you start

- FlutterFlow project with a products collection in Firestore
- Firebase authentication enabled
- Users browsing and purchasing products in your app
- Cloud Functions enabled for batch recommendation processing

## Step-by-step guide

### 1. Create the Firestore schema for behavior tracking and recommendations

Create a user_events collection with fields: userId (String), productId (String), eventType (String: 'view', 'addToCart', 'purchase', 'wishlist'), category (String, denormalized from product), timestamp (Timestamp). Create a subcollection users/{uid}/product_recommendations with fields: productId (String), score (double), reason (String, e.g., 'Customers who viewed X also bought this'), updatedAt (Timestamp). The events collection captures raw behavior data. The recommendations subcollection stores pre-computed results for instant reads. Keep the event weights different: purchase = 10 points, addToCart = 5, wishlist = 3, view = 1.

**Expected result:** Firestore has collections for tracking user behavior events and storing pre-computed recommendations.

### 2. Track user behavior events throughout the app

Add event logging at key interaction points using Action Flows. On product detail page load: create a user_events document with eventType 'view'. On Add to Cart button tap: create an event with 'addToCart'. On successful order completion: create events with 'purchase' for each item in the order. On wishlist toggle: create an event with 'wishlist'. Each event includes the userId, productId, product category (for category-level recommendations), and the current timestamp. Keep event logging as a non-blocking action: do not await the Firestore write so it does not slow down the user's interaction.

**Expected result:** All user product interactions are captured as events in Firestore for recommendation processing.

### 3. Build the Cloud Function for collaborative filtering recommendations

Deploy a scheduled Cloud Function called computeRecommendations that runs every 6 hours. For each active user (has events in the last 30 days), the function: (1) Gets the user's recent product interactions weighted by event type. (2) For each product the user interacted with, finds other users who also interacted with that product. (3) Gets products those other users interacted with that the current user has NOT seen. (4) Scores each candidate product by how many co-users interacted with it, weighted by their event types. (5) Writes the top 10 scored products to the user's product_recommendations subcollection with the score and a reason string explaining the connection.

```
// Cloud Function: computeRecommendations (simplified)
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

const WEIGHTS = { purchase: 10, addToCart: 5, wishlist: 3, view: 1 };

exports.computeRecommendations = functions.pubsub
  .schedule('every 6 hours').onRun(async () => {
    const db = admin.firestore();
    const thirtyDaysAgo = new Date(Date.now() - 30 * 86400000);
    
    // Get active users
    const activeEvents = await db.collection('user_events')
      .where('timestamp', '>', thirtyDaysAgo)
      .get();
    
    const userProducts = {}; // userId -> [{productId, weight}]
    activeEvents.forEach(doc => {
      const e = doc.data();
      if (!userProducts[e.userId]) userProducts[e.userId] = {};
      const w = WEIGHTS[e.eventType] || 1;
      userProducts[e.userId][e.productId] =
        (userProducts[e.userId][e.productId] || 0) + w;
    });
    
    for (const [userId, products] of Object.entries(userProducts)) {
      const userProductIds = Object.keys(products);
      const candidates = {};
      
      // Find co-users and their products
      for (const pid of userProductIds.slice(0, 20)) {
        const coEvents = await db.collection('user_events')
          .where('productId', '==', pid)
          .where('userId', '!=', userId)
          .limit(50).get();
        
        for (const doc of coEvents.docs) {
          const ce = doc.data();
          if (!userProductIds.includes(ce.productId)) {
            // This is unseen by our user — not in their products
          }
          // Get co-user's other products
          const coUserEvents = await db.collection('user_events')
            .where('userId', '==', ce.userId)
            .limit(20).get();
          coUserEvents.forEach(d => {
            const oe = d.data();
            if (!userProductIds.includes(oe.productId)) {
              if (!candidates[oe.productId]) {
                candidates[oe.productId] = { score: 0, reason: pid };
              }
              candidates[oe.productId].score += WEIGHTS[oe.eventType] || 1;
            }
          });
        }
      }
      
      // Write top 10
      const top10 = Object.entries(candidates)
        .sort((a, b) => b[1].score - a[1].score)
        .slice(0, 10);
      
      const batch = db.batch();
      // Clear old recommendations
      const oldRecs = await db.collection('users').doc(userId)
        .collection('product_recommendations').get();
      oldRecs.forEach(d => batch.delete(d.ref));
      
      for (const [prodId, data] of top10) {
        const ref = db.collection('users').doc(userId)
          .collection('product_recommendations').doc(prodId);
        batch.set(ref, {
          productId: prodId,
          score: data.score,
          reason: `Because you viewed a related product`,
          updatedAt: admin.firestore.FieldValue.serverTimestamp(),
        });
      }
      await batch.commit();
    }
  });
```

**Expected result:** The Cloud Function processes user behavior data and writes personalized product recommendations to each user's subcollection.

### 4. Display Recommended for You carousel on the home page

On the home page, add a section titled Recommended for You. Add a horizontal ListView bound to a Backend Query on the current user's product_recommendations subcollection, ordered by score descending, limited to 10. For each recommendation, fetch the product document using the productId to get the product image, name, and price. Display each as a card in the horizontal list: product image (using the CachedImage or thumbnail URL), product name, price, and a small Text showing the reason (e.g., 'Because you viewed Wireless Headphones'). Tapping a card navigates to the product detail page. If the user has no recommendations yet (new user), show a Popular Products section as a fallback.

**Expected result:** The home page shows a personalized horizontal carousel of recommended products with explanation reasons.

### 5. Add Customers Also Bought section on product detail pages

On the product detail page, add a section below the product information titled Customers Also Bought. This uses a different approach than the personalized recommendations: query user_events where productId equals the current product and eventType equals 'purchase'. Collect the userIds of those buyers. Then query their other purchase events to find the most commonly co-purchased products. This can be pre-computed by a Cloud Function that maintains a co_purchases map on each product document: a map of productId to co-purchase count. Display the top 5 co-purchased products as a horizontal ListView with product cards. This section is the same for all users viewing this product, unlike the personalized home page carousel.

**Expected result:** Product detail pages show frequently co-purchased products, encouraging additional purchases.

## Complete code example

File: `FlutterFlow Product Recommendation System`

```text
FIRESTORE SCHEMA:
  user_events (collection):
    userId: String
    productId: String
    eventType: String (view|addToCart|purchase|wishlist)
    category: String (denormalized)
    timestamp: Timestamp
  users/{uid}/product_recommendations (subcollection):
    productId: String
    score: double
    reason: String
    updatedAt: Timestamp
  products (add field):
    coPurchases: Map<productId, count> (precomputed)

EVENT WEIGHTS:
  purchase: 10, addToCart: 5, wishlist: 3, view: 1

EVENT TRACKING (Action Flows):
  Product detail page load → log 'view' event
  Add to Cart tap → log 'addToCart' event
  Order complete → log 'purchase' event per item
  Wishlist toggle → log 'wishlist' event
  All non-blocking (fire and forget)

CLOUD FUNCTION: computeRecommendations
  Schedule: every 6 hours
  For each active user:
    1. Get weighted product interactions (last 30 days)
    2. Find co-users who interacted with same products
    3. Get co-users' other products (user hasn't seen)
    4. Score candidates by weighted co-interaction count
    5. Write top 10 to product_recommendations subcollection
    Each recommendation includes reason string

PAGE: HomePage — Recommended for You
  Section title: "Recommended for You"
  ListView.horizontal:
    Backend Query: product_recommendations orderBy score desc limit 10
    Each card: product image + name + price + reason text
    Fallback (no recs): show Popular Products

PAGE: ProductDetail — Customers Also Bought
  Section title: "Customers Also Bought"
  ListView.horizontal:
    Read product.coPurchases map → top 5 products
    Each card: product image + name + price
```

## Common mistakes

- **Running the recommendation algorithm on the client** — Client-side processing requires reading all user events and product data, which is expensive in Firestore reads, slow on mobile devices, and exposes your recommendation logic and user behavior data. Fix: Run the recommendation algorithm in a Cloud Function. The client only reads pre-computed results from the product_recommendations subcollection, which is fast and secure.
- **Not deduplicating view events for the same product** — A user refreshing a product page 10 times creates 10 view events. This inflates the view signal and skews the recommendation algorithm to over-recommend products users have already seen extensively. Fix: Before logging a view event, check if one already exists for this user and product within the last hour. Skip the duplicate. Alternatively, deduplicate during the recommendation computation.
- **Showing recommendations without any explanation** — Users seeing random product suggestions without context feel surveilled or confused. They do not understand why products are being recommended and are less likely to click. Fix: Include a reason string with each recommendation: 'Because you viewed X', 'Customers who bought Y also bought this', or 'Popular in your favorite category'. This builds trust and increases click-through.

## Best practices

- Run recommendation computations server-side in Cloud Functions on a schedule
- Weight different behavior types: purchases matter more than views
- Include a reason string with each recommendation for transparency
- Pre-compute co-purchase data on product documents for instant detail page reads
- Deduplicate view events to avoid inflating signals from page refreshes
- Show a Popular Products fallback for new users without enough behavior data
- Limit recommendation computation to active users (events in last 30 days) to save resources
- Refresh recommendations every 6 hours for a balance of freshness and compute cost

## Frequently asked questions

### How many behavior events do I need before recommendations work well?

Collaborative filtering needs a critical mass of data. Aim for at least 100 active users with 10+ events each before expecting meaningful recommendations. For new apps, use category-based popular products as a fallback until you have enough data.

### Can I mix collaborative filtering with content-based recommendations?

Yes. Content-based recommendations use product attributes (category, tags, price range) to suggest similar items. Combine both: collaborative filtering for personalized suggestions and content-based for product detail page similarity. Weight and merge the scores.

### How do I prevent recommending products users already purchased?

In the Cloud Function, filter out products the user has already purchased (eventType purchase) from the candidate list. For consumable products that can be re-purchased, you may want to keep them but lower their score.

### Will this work for apps with a small product catalog?

With fewer than 50 products, collaborative filtering adds limited value since users naturally discover most products. For small catalogs, use simpler approaches: category-based suggestions, trending products, or hand-curated collections.

### How much does the recommendation Cloud Function cost?

Cost depends on the number of active users and events. For 1,000 users with 10,000 events, running every 6 hours costs roughly $5-15 per month in Cloud Functions compute. Monitor execution time and optimize queries to control costs.

### Can RapidDev help build recommendation systems?

Yes. RapidDev can build sophisticated recommendation engines with collaborative filtering, content-based filtering, real-time personalization, A/B testing of algorithms, and analytics dashboards to measure recommendation effectiveness.

---

Source: https://www.rapidevelopers.com/flutterflow-tutorials/how-to-create-a-product-recommendation-system-based-on-user-behavior-in-flutterflow
© RapidDev — https://www.rapidevelopers.com/flutterflow-tutorials/how-to-create-a-product-recommendation-system-based-on-user-behavior-in-flutterflow
