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.
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
Step 1 : - Create Cloud Function ( link) to get image in binary format.
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");
}
});
});
response.data
will now contain the image data in binary format and send it as a response.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.firebase deploy
in terminal to deploy the cloud function.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');
}
}
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.
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.
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: