rhondamuse.com

Effortlessly Store and Manage Files in Firebase Storage with Flutter

Written on

Chapter 1: Introduction to Firebase Storage

In this guide, we will explore how to configure and utilize Firebase Storage for reading and writing data from your Flutter application.

Where Are My Files?

This article previously contained outdated information. For the latest updates, refer to the revised version here! Firebase Storage is a cloud-based object storage service that allows you to store and serve various types of data, such as user profile images or documents uploaded during user registration. This guide will cover the essential steps to set it up, including basic access control configurations. Here’s what we will discuss:

  • Setting up Firebase Storage
  • Writing data
  • Reading data
  • Deleting data
  • Monitoring storage usage
  • Access control
  • Differences between Firestore and Storage
  • Resolving CORS issues for web applications

If you're interested in comprehensive details, consider checking out my ebook that offers in-depth guidance on developing Flutter applications with Firebase, available for purchase on Gumroad!

To follow along with the code examples provided here or those on my GitHub page, you'll need to create your own Firebase project. If you haven't done this yet, I have a helpful article that outlines the necessary steps.

Setting Up Firebase Storage

The first step involves installing the firebase_storage package. Next, you need to create a storage bucket, which acts like the root directory of a file system. This can be accomplished through the Firebase Console.

  1. Navigate to Storage → Get Started.
  2. Select "Start in test mode" and click Next (we will revisit access control later).
  3. Choose your preferred location and confirm by clicking Done. For more information on location benefits, click here. It's advisable to choose a location that aligns with your target audience.

Once this setup is complete, you will have a default bucket available for storing your data, with the option to create additional buckets as needed.

Let’s dive into data management! 🎉

StorageReference

To interact with your storage bucket, first obtain a StorageReference object that points to a file or directory. You can traverse the reference tree using the child() method along with the root and parent properties. Google Cloud Storage URIs and HTTPS URLs are also supported for creating references.

Reading Data

Assuming you have several files stored at the root level of your bucket, you may want to download them. The following code retrieves five items from the storage reference, downloads their contents, and accesses the metadata.

To control the number of results retrieved, utilize the ListOptions object, which includes maxResults and pageToken. The getData() method fetches the content as a byte array, getMetadata() retrieves detailed file information, and getDownloadURL() provides a link to the file or folder. For folders, use files.prefixes instead of files.items.

Writing Data

How do we upload data to our storage bucket? The simplest method is through the Firebase Console, where you can find buttons for uploading files and creating folders.

However, as developers, we often prefer coding. Here’s a brief example of how to upload a file programmatically.

Using a Reference and the putFile() method, you can upload a File object. The targetName can also specify a path with a filename, allowing it to be stored in a designated subfolder. While file pickers are commonly used to select files, you can also create and write files directly.

The putFile() method returns an UploadTask object, enabling you to monitor the upload process. This example illustrates how to listen to the event stream and update a progress indicator during the upload. The UploadTask object also provides methods to pause, resume, or cancel the upload. For longer operations, you have various tools to keep the user informed about the status. 👍

Deleting Data

Deleting files is straightforward: simply acquire a reference to the item (file) or prefix (folder) and invoke the delete() method. Simple, right? 😎

Monitoring Storage Usage

To keep track of your current storage usage, visit your Firebase Storage Usage dashboard. This information updates daily, and you will benefit from a free tier before incurring any charges.

You might be curious as to why there is already space occupied even if you haven't used the database yet. This is likely due to deployed cloud functions. These buckets are not visible in Firebase but can be viewed in the Google Cloud Console. Avoid deleting these buckets if you have active cloud functions!

Refer to this link for further details on why you might incur charges, even if everything appears to be within the Firebase free quota.

Access Control

I previously discussed this in my article on Cloud Firestore. Here’s a quick recap since the approach is similar.

Access control ensures that data operations occur as intended. There are various ways to configure rules, but here’s a brief overview. Your current rule might look something like this:

rules_version = '2';

service firebase.storage {

match /b/{bucket}/o {

match /{allPaths=**} {

allow read, write: if false;

}

}

}

The initial line identifies the service being used, as rules can also apply to Cloud Firestore and the Realtime Database. The subsequent match statement(s) specify the paths for which the rule applies. You can nest multiple match statements or use a single one. The allow statement indicates the conditions under which access is granted. Available methods include:

  • get — read single documents
  • list — read queries
  • create — write new documents
  • update — write existing documents
  • delete — remove data
  • read — includes both get and list
  • write — combines create and update

Commonly, match statements utilize wildcards. Text within curly brackets, such as {bucket}, serves as a single-segment wildcard and can be used in conditions. To make the wildcard recursive, use two asterisks: {allPaths=**}.

The example rule above denies all read and write access across all paths in all buckets. Here are some common rule conditions for your reference:

allow read, write: if false; // no access

allow read, write: if request.auth != null; // access when authenticated

match ... {

allow read: if true; // read access for everyone

allow write: if request.auth != null; // write access when authenticated

}

A solid starting rule checks for user authentication, preventing unauthorized access to your data. As your application expands, your rules may need to become more complex.

Firestore vs Storage

When should you use each service? Firebase Cloud Firestore is a NoSQL database designed for storing data types like strings, numbers, booleans, or complex JSON objects. Conversely, Firebase Storage is intended for larger data sets, such as images, PDF files, videos, or user-generated content.

If you were to store an image in Firestore, you would likely attempt to convert it into a Base64 string. However, Firestore has limitations that would complicate this approach, so it’s best to utilize Storage for such tasks.

CORS Issues for Web Applications

If you're developing for the web, you might encounter download issues due to CORS errors. To resolve this, install the Google Cloud CLI and set a CORS rule for your bucket. Create a file named cors.json and fill it with the following content:

[

{

"origin": ["*"],

"method": ["GET"],

"maxAgeSeconds": 3600

}

]

To deploy the rule, run the following command:

gsutil cors set cors.json gs://<your-bucket-name>

After completing these steps, the CORS error should be resolved. For additional details, please refer to the documentation.

Conclusion

Firebase Storage offers a fast and user-friendly solution for allowing your users to store their content seamlessly. This guide has equipped you with the necessary steps to set up your storage, as well as read and write data effectively. For a visual demonstration of the source code, check out the following video.

The complete source code example can be found on my GitHub page.

This article is part of the Flutter Firebase Compendium, which includes numerous tutorials and guides on how to leverage Firebase with Flutter applications. Enhance your understanding of Firebase for Flutter development through my ebooks.

The following video provides additional insights on uploading files to Firebase Storage in Flutter, which may further assist you.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Mind Clearing Strategies for ADHD: The Essential Guide

Discover effective techniques for managing ADHD thoughts and enhancing mental clarity.

Exploring the World's Mud Volcanoes: Nature's Quirky Phenomena

Discover the intriguing world of mud volcanoes, their dynamics, and the risks they pose, along with notable examples like the Lusi eruption.

My Motivation Reservoir is Overflowing: How My Manager Boosted My Spirits

Discover how a simple conversation with my manager filled my motivation tank and improved my engagement at work.

Unlocking the Secrets of Black Hole Information Loss

Explore the enigma of information loss in black holes and the theories that seek to explain this cosmic puzzle.

Keeping Tabs on Kaya: My Journey with a Dog GPS Tracker

Discover the benefits of using a GPS collar for your dog, featuring the Whistle Go Explore that tracks your pet's every move.

Innovative Methods for Measuring Elevator Travel Distance

Explore unique techniques to estimate elevator travel distance using digital scales and smartphone accelerometers.

The Dystopian Future of Advertising: A Cautionary Tale

As technology evolves, advertising risks crossing ethical boundaries, affecting our privacy and mental health.

Harnessing GPT-Engineer for Streamlined Code Creation

Discover how GPT-Engineer enhances coding efficiency through its innovative questioning approach and code generation capabilities.