Dom Maurice

View Original

Flutter + Firebase Storage and Loading Images

I am learning how powerful using Firebase as my backend is that I can pull in the resources as I need them. But I have to problem-solve a lot, and here I have an interesting problem with loading images from Firebase Storage in a Flutter app for the web.

The Problem

In Firebase, I have created a bucket and a .png file inside it.

In my code, I access the file with:

Image.network(firebaseStorageUrl);

Now running my app leads to:

Y tho?

We are accessing another resource with a different domain over the web the Cross-origin resource sharing becomes a thing.

Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

Basically, I am a webserver with resources and I will let you know if you can use them or not.

Solution

Download and install gsutil, a command line tool for Google Cloud.

From the installer, you can open a shell and run

gcloud init

You will be prompted with the following:

Welcome! This command will take you through the configuration of gcloud.
Your current configuration has been set to: [default]
To continue, you must login. Would you like to login (Y/n)?

Type “y” to open a browser and allow access, then type:

copy NUL cors.json

This will create an empty file with that name. Open that file by navigating to the folder in the command prompt. Add to it:

[
  {
    "origin": ["*"],
    "method": ["GET"],
    "maxAgeSeconds": 3600
  }
]

Save the file and go back to the command prompt. Then type:

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

And you should be done.