Intermediate

Oct 10, 2024

Building a rating system in FlutterFlow with Firebase

In today's app-driven world, rating systems play a crucial role in determining user satisfaction and building trust. Whether you're running a food delivery app, an e-commerce store, or a marketplace, a well-implemented rating system ensures transparency and helps users make informed decisions.

In this blog, we'll walk through the steps to create a comprehensive rating system using Firebase, complete with a setup for collecting reviews, subcollections, and a Cloud Function that updates an average rating in the parent collection.


1. Setting up the rating system

Let's say we're building a restaurant review app. Users will be able to leave reviews and rate their dining experience. Each restaurant will have a subcollection for reviews, and the ratings will be averaged using a Cloud Function that updates the parent restaurant collection.

Firebase structure example

Restaurants collection:

  • Each document represents a restaurant (e.g., restaurants/{restaurantId})

  • Fields:

    • name: The name of the restaurant

    • location: Location of the restaurant

    • average_rating: Average rating (to be updated based on reviews)

    • total_reviews: The total number of reviews

Subcollection for reviews:

  • Each restaurant has a reviews subcollection (e.g., restaurants/{restaurantId}/reviews)

  • Fields for each review document:

    • user_id: The ID of the user leaving the review

    • rating: The rating given (e.g., 1-5 stars)

    • comment: Optional text feedback from the user

    • timestamp: The time the review was created

This simple setup provides flexibility to manage user reviews without overloading the main restaurant collection.


2. Creating the review collection

To set up the subcollection for reviews in FlutterFlow:

  1. Collection creation: First, create the reviews subcollection under the restaurant collection. Each time a user submits a review, a new document will be created in this subcollection with the fields mentioned above.

  2. Review submission UI: In FlutterFlow, you can build a form where users can input their rating and feedback. When they submit the form, the data will be added to the reviews subcollection for the respective restaurant.

Sample review document

{  
  "user_id": "user123",  
  "rating": 4,  
  "comment": "Great food, but the service was slow.",  
  "timestamp": "2024-10-01T10:15:00"
}


3. Cloud Function to calculate the average rating

The core part of this rating system is calculating the average rating for each restaurant whenever a new review is added. We'll set up a Cloud Function to listen to new documents in the reviews subcollection and update the average_rating and total_reviews fields in the parent restaurants collection.

Sample Cloud Function

const functions = require("firebase-functions");
const admin = require("firebase-admin");


exports.updateRestaurantRating = functions.firestore.document('restaurants/{restaurantId}/reviews/{reviewId}')
.onCreate(async (snap, context) => {    
	// Get the restaurant ID    
    const restaurantId = context.params.restaurantId;    
    // Get the new review's rating    
    const newRating = snap.data().rating;    
    
    // Reference to the parent restaurant document    
    const restaurantRef = admin.firestore().collection('restaurants').doc(restaurantId);    
    
    try {      
    	// Get the current restaurant data      
        const restaurantDoc = await restaurantRef.get();      
        const restaurantData = restaurantDoc.data();
        
        // Get the current average rating and total reviews      
        const currentAverage = restaurantData.average_rating || 0;      
        const totalReviews = restaurantData.total_reviews || 0;
        
        // Calculate the new average rating      
        const updatedTotalReviews = totalReviews + 1;      
        const updatedAverageRating = ((currentAverage * totalReviews) + newRating) / updatedTotalReviews; 
        
        // Update the restaurant document      
        await restaurantRef.update({average_rating: updatedAverageRating, total_reviews: updatedTotalReviews});      
        console.log(`Restaurant ${restaurantId} updated with new average rating: ${updatedAverageRating}`);
    } catch (error) {      
    	console.error('Error updating restaurant rating:', error);    
    }  
});


How it works:

  • Trigger on create: This function is triggered every time a new review is added to the reviews subcollection of a restaurant.

  • Calculate average: It fetches the current average rating and total reviews from the parent restaurant document, then calculates the new average rating.

  • Update parent collection: The function updates the parent restaurant document with the new average rating and the updated total number of reviews.


4. Displaying the average rating

Once the average rating is calculated and stored in the average_rating field of the restaurant document, you can display it in your FlutterFlow app on the restaurant profile page. Use a simple query to fetch the restaurant data and bind the average_rating field to your UI.

You can also style the rating with stars or any custom design using FlutterFlow's widgets (or build your own).


5. Adding additional features

If you'd like to extend the rating system further, here are some additional features you can implement:

  • User restriction: Ensure that users can only leave one review per restaurant. You can achieve this by checking if a review by the user already exists before allowing them to submit a new one.

  • Review sorting: Allow users to sort reviews by newest, highest rated, or lowest rated.

  • Rating breakdown: Display a rating breakdown (e.g., how many users rated 5 stars, 4 stars, etc.) on the restaurant profile page.


Conclusion: Ready to implement your own rating system?

By following these steps, you'll have a robust rating system that calculates average ratings in real-time, ensuring your users have an accurate reflection of each restaurant's performance. The combination of Firebase and FlutterFlow makes this process straightforward and scalable.

And if you're looking to implement a rating system like this without building it from scratch, you can reach out to us and we'll help you build it!