Retrieve image from Firebase storage and store in FlutterFlow Page state(Uploaded File (Bytes)) variable
Knowledge

Retrieve image from Firebase storage and store in FlutterFlow Page state(Uploaded File (Bytes)) variable

Learn how to Retrieve image from Firebase storage and store in FlutterFlow Page state

Pankaj Sharma
Flutterflow development company
February 10, 2025
Table of content

Overview:

This article explains how to retrieve an image from Firebase Storage and store it in FlutterFlow's Page State as an Uploaded File (Bytes). It covers fetching the image URL, converting it into byte format, and saving it in Page State for easy access across screens.

Prerequisites

  • Firebase
  • FlutterFlow
  • Node js
  • Cloud Functions

Note : - Hello FlutterFlow Enthusiast, in this article we are not going to teach you, how to integrate firebase in flutterflow, how to upload image in firebase storage, how install Node.js and how to make cloud function, we are just focus on how can we Retrieve image from Firebase storage and store in FlutterFlow Page state(Uploaded File (Bytes)) variable.

If you guys still want to know how to make cloud function and other stuff, you can check out our below article : -https://www.flutterflowdevs.com/blog/how-admin-can-change-password-of-other-authenticate-users

Steps to achieve our goal : -

Step 1 : - Create Cloud Function ( link) to get image in binary format.

  • Cloud Function code
    • Retrieves a random image from Firebase Storage.
    • Uses CORS middleware to allow cross-origin access.
    • Uses Axios to fetch the image in binary format.
    • Returns the image directly in the response.
    • Uses Signed URLs to access Firebase Storage securely.
    const functions = require("firebase-functions");

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

    const {getStorage} = require("firebase-admin/storage");

    const axios = require("axios");

    const cors = require("cors"); // Import CORS

    const serviceAccount =

    require("./your-service-account-file.json");



    if (!admin.apps.length) {

     admin.initializeApp({

       credential: admin.credential.cert(serviceAccount),

       storageBucket: "your-project-id.appspot.com",

     });

    }



    const getRandomImage = async (userId) => {

     try {

       const storage = getStorage().bucket("your-project-id.appspot.com");

       const folderPath = `users/${userId}/uploads/`;



       // List all files in the user's folder

       const [files] = await storage.getFiles({prefix: folderPath});



       if (!files.length) {

         console.log("No images found.");

         return null;

       }



       // Pick a random image

       const randomIndex = Math.floor(Math.random() * files.length);

       const file = files[randomIndex];



       // Get the download URL

       const [signedUrl] = await file.getSignedUrl({

         action: "read",

         expires: "03-01-2500", // Set expiration date accordingly

       });



       console.log(signedUrl);

       return signedUrl;

     } catch (error) {

       console.error("Error fetching image:", error);

       return null;

     }

    };



    // Add CORS to your function

    exports.getRandomImage = functions.https.onRequest((req, res) => {

     // Enable all CORS requests (you can specify more restrictive rules if needed)

     cors()(req, res, async () =>{

       try {

         const {userId} = req.query;



         if (!userId) {

           return res.status(400).send("User ID is required");

         }



         const imageUrl = await getRandomImage(userId);

         if (!imageUrl) {

           return res.status(404).send("No images found");

         }



         const response = await axios.get(imageUrl, {responseType: "arraybuffer"});

         res.set("Content-Type", "image/png");

         res.send(response.data);

       } catch (error) {

         console.error("Error fetching image:", error);

         res.status(500).send("Error fetching image");

       }

     });

    });



    • This function need userId as a parameter.
    • response.data will now contain the image data in binary format and send it as a response.
  • Now deploy the cloud function.
    • We can remove const serviceAccount = require("./your-service-account-file.json"); and credential: admin.credential.cert(serviceAccount)  lines from the code, the serviceAccount only required to run the code locally.
    • Now write the command firebase deploy  in terminal to deploy the cloud function.
    • You will get url in terminal something like http://us-central1-firebase_project_id/yourfunction.
    • Just copy that url and save somewhere. we will use it in our flutterflow custom action.

Step 2 : - Create custom action which return FFUploadedFile type value, just need to pass userId as a parameter.

// Automatic FlutterFlow imports

import '/backend/backend.dart';

import '/flutter_flow/flutter_flow_theme.dart';

import '/flutter_flow/flutter_flow_util.dart';

import '/custom_code/actions/index.dart'; // Imports other custom actions

import '/flutter_flow/custom_functions.dart'; // Imports custom functions

import 'package:flutter/material.dart';

// Begin custom action code

// DO NOT REMOVE OR MODIFY THE CODE ABOVE!



import 'dart:typed_data';



import 'package:http/http.dart' as http;



Future<FFUploadedFile> fetchUserImageAsFFFile(String userId) async {

 // Add your function code here!

 try {

   // Fetch image bytes from the URL

   // final response = await http.get(Uri.parse(imageUrl));

   final response = await http.get(Uri.parse(

       'cloud_function_url?userId=$userId'));



   if (response.statusCode == 200) {

     Uint8List imageBytes = response.bodyBytes;



     return FFUploadedFile(

       name: 'image.jpg', // You can modify this if needed

       bytes: imageBytes, // Store the image bytes

       height: null, // You can extract this if needed

       width: null, // You can extract this if needed

       blurHash: null,

     );

   } else {

     throw Exception('Failed to load image');

   }

 } catch (e) {

   print('Error loading image: $e');

   return FFUploadedFile(name: 'error.jpg');

 }

}

  • You just need to add cloud_function_url which you already copied from step 1.
  • Ex : -
  • final response = await http.get(Uri.parse(

           '***http://us-central1-firebase_project_id/yourfunction***?userId=$userId'));

Step 3 : - Now we are going to create a simple page in flutterflow, which contain a image and a button widget.

  • Create a page state variable named as imgFFUploadedFile ( Uploaded File (Bytes) ).
  • When we click on button ( Update Local Variable ), we call fetchUserImageAsFFFile and pass userId ( Authenticate User ID ) and this custom action return image as a FFUploadedFile( userImageAsFFFile ).
  • After that we will store that action output ( userImageAsFFFile ) inside imgFFUploadedFile page state variable.

Step 4 : - To check, we really got the image from firebase storage, we created a custom function getImage and pass imgFFUploadedFile as a parameter, this function return image.

import 'dart:convert';

import 'dart:math' as math;



import 'package:flutter/material.dart';

import 'package:google_fonts/google_fonts.dart';

import 'package:intl/intl.dart';

import 'package:timeago/timeago.dart' as timeago;

import '/flutter_flow/custom_functions.dart';

import '/flutter_flow/lat_lng.dart';

import '/flutter_flow/place.dart';

import '/flutter_flow/uploaded_file.dart';

import '/backend/backend.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

import '/auth/firebase_auth/auth_util.dart';



String getImage(FFUploadedFile? imgFFUploadedFile) {

 /// MODIFY CODE ONLY BELOW THIS LINE



 if (imgFFUploadedFile == null || imgFFUploadedFile.bytes == null) {

   return 'No image available';

 }



 // Convert image bytes to Base64 string

 String base64Image = base64Encode(imgFFUploadedFile.bytes!);

 return 'data:image/png;base64,$base64Image';



 /// MODIFY CODE ONLY ABOVE THIS LINE

}

Step 5 : - Now we will integrate getImage custom function with image widget path.

Conclusion

This article provides a step-by-step guide on retrieving an image from Firebase Storage and storing it as an Uploaded File (Bytes) in FlutterFlow’s Page State. It explains how to:

  1. Create a Cloud Function to fetch a random image in binary format.
  2. Develop a custom FlutterFlow action to call the function and store the image.
  3. Use a Page State variable to store and display the image dynamically in the UI.By following these steps, developers can efficiently manage and display Firebase images in FlutterFlow apps.

Retrieve image from Firebase storage and store in FlutterFlow Page state(Uploaded File (Bytes)) variable

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