Pagination in Flutterflow web project Firebase
Knowledge

Pagination in Flutterflow web project Firebase

Learn Pagination in Flutterflow web project (Firebase)

Pankaj Sharma
Flutterflow development company
January 31, 2025
Table of content

Overview

Pagination is the process of dividing a large set of data into smaller chunks or "pages," which are retrieved and displayed one at a time. This is especially important for web applications to optimize performance and enhance the user experience when dealing with extensive datasets.

Prerequisites

  • FlutterFlow
  • Firebase
  • Google Cloud Functions

Firebase

Firebase is a Google platform offering tools to build, improve, and scale apps across mobile, web, and desktop, with services like real-time databases, authentication, and serverless backend solutions.

To set up your Firebase project, please follow the steps below:

1. Create a Firebase Project

  • Go to the Firebase Console.
  • Click Create a project and follow the instructions to set up a new project.

2. Enable Firebase Authentication

  • In the Firebase console, go to the Authentication section.
  • Click Get Started and enable the sign-in methods you need (e.g., Email/Password, Google).

3. Create Database

  • In the Firebase console, go to Cloud Firestore > Create database.
  • Set the location and name of the database.
  • Choose secure rules to start in test mode.
  • Start a collection.

4. Create Service Account for Admin SDK

  • Go to Project settings > Service accounts.
  • In the Firebase Admin SDK section, select Node.js from the Admin SDK configuration snippet, and click Generate new private key. This will download a JSON file, which you'll use in your backend service.

5. Enable Cloud Functions

  • To use Cloud Functions, your project must be on the Blaze Plan. By default, every Firebase project is on the Spark Plan.
  • In the Firebase Console, click Upgrade from the left menu, select the Blaze Plan, and choose a billing account. Then, navigate to the Functions tab on the left sidebar and follow the instructions to enable Cloud Functions for your project.

Node.js

Node.js is commonly used in Firebase Cloud Functions because Firebase Functions are built on top of Google Cloud Functions, which are serverless functions that execute JavaScript (or TypeScript) code. Since Node.js is a JavaScript runtime, it's the perfect environment for writing and deploying backend logic in Firebase.

Steps to Install Node.js:

  • Download the Installer:
    • Go to the official Node.js website here.
    • Choose the recommended version for your operating system (LTS is usually preferred for stability).
  • Run the Installer:
    • Open the downloaded file and follow the installation prompts. Make sure to select the option to install Node.js and npm (Node Package Manager).
  • Verify Installation:
    • Once installed, open your terminal/command prompt and type the following commands.

node -v

  • Update npm (Optional):
    • You can update npm to the latest version using the command:

npm install -g npm@latest

Google Cloud Functions

Google Cloud Functions is a serverless platform that lets you run small, event-driven functions without managing servers, automatically scaling based on demand. In this guide, we'll use Cloud Functions to securely handle backend tasks for password changes.

Steps to Install Firebase CLI for Cloud Functions:

  • Open the Command Prompt and create a new folder using the command:

C:\\>mkdir Firebase_API

  • Open the Firebase_API folder in your code editor. I am using Visual Studio Code as my default code editor; you can use any editor you prefer.
  • Use the following command to open the folder:

C:\\>cd Firebase_API

  • Ensure that npm is installed on your local machine. To do that, run the below command in your terminal:

node -v

  • Open your terminal and run the following command to install the Firebase CLI globally:

npm install -g firebase-tools.

  • To confirm that the Firebase CLI is installed correctly, run the command:

firebase --version

  • To connect the Firebase CLI to your Firebase account, run the following command:

firebase login

  • It will then ask the question: “Allow Firebase to collect CLI and Emulator Suite usage and error reporting information?” Proceed by selecting YES.
  • Initialize the Firebase project by running the command :

firebase init

  • Which Firebase features do you want to set up for this directory? Press Space to select features, then press Enter to confirm your choices. Select “Functions: Configure a Cloud Functions directory and its files.
  • Select your firebase project.
  • Which language would you like to use to write Cloud Functions? Select “JavaScript” .
  • “Do you want to use ESLint to catch probable bugs and enforce style?” Answer "Yes" to confirm.
  • “Do you want to install dependencies with npm now?” Answer "Yes" to confirm.
  • Firebase initialization is now completed.
  • After this, a folder named “functions” will be created within the “firebase_auth” folder.

Cloud Function Code

  • Now open that “functions” folder by your code editor.
  • Install “express” module by below command :

npm install express

  • Install “firebase-admin” module by below command :

npm install firebase-admin

  • Install “cors” module by below command :

npm install cors

  • Open index.js file in Visual Studio Code

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

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

const express = require("express");

const cors = require("cors");



// Initialize Firebase Admin SDK

const serviceAccount = require("./permissions.json");



admin.initializeApp({

   credential: admin.credential.cert(serviceAccount),

   databaseURL: "<https://mahesh-af1b-default-rtdb.firebaseio.com>",

// Enter the database URL here



});



const db = admin.firestore();

const app = express();



// Middleware

app.use(cors({ origin: true }));

app.use(express.json()); // Ensure JSON body parsing



// Get or Read

app.post("/api/read", async (req, res) => {

   try {

       const datalimit = parseInt(req.body.datalimit) || 10; // Default limit is 10

       const pageNumber = parseInt(req.body.pageNumber) || 1; // Default page number is 1



       if (pageNumber < 1) {

           return res.status(400).send({ success: false, error: "Invalid page number" });

       }



       const offset = (pageNumber - 1) * datalimit; // Calculate offset



       // Count total documents in the collection

       const totalDocsSnapshot = await db.collection("Products").get();

       const totalDocuments = totalDocsSnapshot.size; // Total document count



       // Calculate total pages

       const totalPages = Math.ceil(totalDocuments / datalimit);



       // Fetch paginated data

       const query = db.collection("Products").orderBy("name").offset(offset).limit(datalimit);

       const querySnapshot = await query.get();



       const response = querySnapshot.docs.map((doc) => ({

           id: doc.id,

           ...doc.data(),

       }));



       return res.status(200).send({

           success: true,

           data: response,

           totalDocuments, // Include total document count

           totalPages, // Include total pages

           pageNumber,

           datalimit,

       });

   } catch (error) {

       console.error(error);

       return res.status(500).send({ success: false, error: error.message });

   }

});



// Export the API to Firebase Cloud Functions

exports.app = functions.https.onRequest(app);



  • For Firebase Admin SDK go to firebase console then Project overview > Project Settings > Service accounts.
  • save the file in the same folder of cloud function.
  • Open firebase.json file then put the code in the file.



{

 "functions": {

   "source": "functions"

 },

 "projects": {

   "default": "mahesh-af1b"

   //   We can put the function name here by default.

 }

}



  • Replace'./path/to/your-service-account-file.json' with the path to the JSON file you downloaded from the Firebase Admin SDK.
  • Additionally, make sure to save that JSON file in the same folder.

Deploy Cloud Function

Run the command to deploy the project to Firebase:

firebase deploy

Flutterflow

FlutterFlow is a low-code development platform built on top of Flutter, Google's open-source UI toolkit for building natively compiled applications for mobile, web, and desktop from a single codebase.

To set up your FlutterFlow project, please follow the steps below:

1. Create a Flutterflow project

  • Go to the Flutterflow console.
  • Click on Create a project and follow the instructions to set up a new project.

2. Connect FlutterFlow with Firebase

  • Copy the Project ID from Firebase > Project Settings > General.
  • Open FlutterFlow > Settings > Firebase.
  • In Firebase Project ID, enter the project ID from Firebase to connect it.

3. Create API Call in flutterflow

  • Open flutterflow > API calls
  • In the API URL past the URL that was generate after cloud function deploy. additional thing to add with AP_URL/api/read
  • create Post API in the in the API group that has two variable pageNumber and dataLimit of integer type.
  • define the API body in JSON with the variables save.

{

 "pageNumber": <pagenumber>,

 "datalimit": <datalimit>

}

  • Api Response.

{

   "success": true,

   "data": [

       {

           // Document 1

       },

       {

           // Document 2

       },

       -

       -

       -

   ],

   "totalPages": <totalPages>,

   "pageNumber": <pagenumber>,

   "datalimit": <datalimit>

}

4. Create the data table.

  • Create a static data table for pagination.
  • Call the API on the Page Load action.
  • The API returns four arguments:
    • Total Pages
    • Page Number
    • Data Limit

Add functionality to the Back/Next arrow buttons for incrementing or decrementing the page number. Then, call the API with the updated page number and data limit.

  • Disable the Back arrow button if the page number is equal to 1, and disable the Next arrow button if the page number is equal to the total number of pages.
  • Set the action on the left arrow button so that the page number cannot be less than one, and on the right arrow button, ensure the page number does not exceed the total number of pages.

Conclusion

Implementing pagination in a FlutterFlow web project with Firebase as the backend is a crucial strategy for efficiently managing and displaying large datasets.

Pagination ensures that only a limited number of records are fetched and displayed at a time. This reduces memory and bandwidth usage, leading to faster load times and a smoother user experience.

Pagination in Flutterflow web project Firebase

Ex- Technical Lead at Paytm Money | Senior Software Developer | NIT Surathkal

Flutterflow project image

Need expert help in Flutterflow and Firebase?

Contact Us
Flutterflow development company

View more blogs

Ready to develop your own product? Get in touch today!

Get in Touch  
Flutterflow app development
Whatsapp icon