As you want to store an image to the cloud storage, in the FirebaseHelper class let’s create a method that uploads a file into the Firebase Cloud Storage bucket.
It returns a Future of a boolean. Call it uploadImage. This takes a File object, that we can simply call file. Use the code actions to automatically import the dart:io package, that contains the File class.
To upload and retrieve files form a Cloud Storage instance, you use an object called Reference. The reference is a pointer to a file, that must be unique within your bucket.
For this project we can create a base path where we want to place all our files: you could think of it as a kind of folder. As we will use it both for uploading and downloading images, let’s declare it at the top of the FirebaseHelper class. It will be a final, called folder, that will take a string, with activity_images.
final folder = 'activity_images/';
Now back to the uploadImage method, let’s declare a final, called path, that takes our base path and the basename of the path of the file that has been passed as a parameter. The basename method removes from the path of the file everything except the file name. It’s included in the path.dart package, so let’s use the code actions to import that one as well.
final path = folder + basename(file.path);
Now we can upload the file to Cloud storage. So, await storage.ref, passing the path: this returns a Reference object, even if the file does not exist yet. On the Reference object, just call the put method, passing the file. This will attempt to upload the file to the Cloud storage. Then return true.
await storage.ref(path).putFile(file);
return true;
Now, there are several things that could go wrong while uploading a file: you could lose your network connection, or you might not have the right permissions, or you could get a timeout error… So, even in a tutorial like this one, it’s better to include those two lines of code in a try – catch block. Let’s use the code actions to surround this code with a try catch. In the catch block, let’s just return false.
That’s it: to upload a file to Storage you just need a file, a reference object, and the putFile method.
Next let’s use this method from the Activity detail screen.