7.0 Introduction

Firebase Storage is a robust, scalable solution for storing and serving user-generated content such as photos, videos, and other large files.

Unlike Firestore, which is optimized for structured data and real-time synchronization, Firebase Storage is designed to handle large binary files efficiently.

Storing large files in Firebase Storage is advantageous because it provides high-performance uploads and downloads, robust security via Firebase Security Rules, and seamless integration with other Firebase services.

By storing large files in Firebase Storage and then including references to these files in Firestore documents, you optimize your app's performance and ensure that your database remains efficient and responsive, as Firestore is not intended for storing large blobs of data.

This separation allows Firestore to manage structured data and real-time updates effectively while Firebase Storage handles the heavy lifting of large file management.

7.1 Firebase Storage in Practice

Lets go back to our demo app example. If we want to allow users to upload images, it wouldn’t be efficient to store these image files in a Firestore document. Instead we should use Firebase Storage to store these files, and then save a reference to the file in the Firestore document.

How can we do this? Well the process looks something like this.

  1. Importing packages
import 'package:cloud_firestore/cloud_firestore.dart'; // Upload to Firestore
import 'package:firebase_storage/firebase_storage.dart'; // Upload to Firebase Storage
  1. Upload the file to Firebase Storage and save the download url
final postsRef = FirebaseStorage.instance.ref().child('posts');
XFile? image;

...
// Perform some kind of io logic to assign an image to the image variable above.
// An option to do this is the image_picker package which you will need to install
// with a "flutter pub add image_picker" in your terminal.
...

Function upload = () async {
	String? imageUrl = null;
	
	if (image != null) {
	  // Add Image to firebase storage
	  final imageRef = postsRef.child("IMG - ${DateTime.now()}");
	
	  File imageFile = File(image!.path);
	
	  await imageRef.putFile(imageFile);
	
	  imageUrl = await imageRef.getDownloadURL(); // Saving the URL to save in Firestore
	  
  	...
		// TODO: Add Firestore logic
		...
	  
	}
};
  1. Upload to Firestore and reference the download url form Firebase storage
Function upload = () async {
	String? imageUrl = null;
	
	...
	// Firebase Storage Logic
	...
	
	// Add to Firestore
	CollectionReference posts = FirebaseFirestore.instance.collection('posts');
	
	await posts.add({
	  "title": title,
	  "content": content,
	  "imageUrl": imageUrl,
	  "date": DateTime.now()
	});
};