Introduction

Before we start implementing Firebase Storage, we should be aware of what Firebase Storage is. So, Firebase Storage is a cloud storage solution provided by Google which uploads and downloads user content like images, audio, video, PDF, etc. from Android, iOS devices or from the web. It has the capability to scale automatically as per the customer’s requirement. You can define user-specific security using security rules and the upload and download manager which handles a poor internet connection, and you do not need to keep track of activities.

Note - This article is one of the parts of our series on chat apps in Flutter using Firebase. Our chat app series is one of the best examples to make chat apps in Flutter using Google Firebase. If you are interested in the chat app, you can check out my whole series. So, let’s implement it.

In this example, we will create a simple app to upload the user-selected image uploaded to Firebase Storage and show it uploaded on the same screen.

End Result

Firebase Project Setup Steps

Step 1

The first and most basic step is to create a new application in Flutter. If you are a beginner in Flutter, then you can check my post, Create a first app in Flutter. I have created an app named “flutter_chat_app”.

Step 2

Now, you need to set up a project in Google Firebase. Follow the below steps for that. Please follow the steps very carefully.

  • Go here and add a new project. I will share the screenshot so you will get a better idea.

  • Click on “Add Project” to add a new project in Google Firebase. Then, you will find the below form.

  • Give a project name and accept the terms and condition and click on “Create Project”. It will take some time to create a new project and redirect you to the “Project Overview” page.

  • Now, you need to add an Android app in this project. You can add new Android project by clicking on the Android icon. You can also add iOS project if you want to create an iOS application for the same.

  • In Project Overview, add an Android app. It will open a new form.

  • Android package name can be found in the AndroidManifest.xml file in the Android/App folder of your project.

  • App nickname is optional.

  • For SHA-1 generation, go here.

  • In step 2, download google-service.json and put in Android => App folder of your project

  • In step 3, you can see you need to configure some dependencies.

Project-level build.gradle (/build.gradle): means build.gradle file in Android folder directly,

buildscript {    
 dependencies {    
 // Add this line    
 classpath 'com.google.gms:google-services:4.2.0'    
 }    
} 

App-level build.gradle (//build.gradle): means build.gradle file in Android = > App folder

// Add to the bottom of the file    
apply plugin: 'com.google.gms.google-services’  

Note We don’t need to add implementation ‘com.google.firebase:firebase-core:16.0.9’ in dependencies

  • In Step 4 it will try to verify your app. For that, you need to run your app once or you can skip this step.

  • Hooray :) Your android app has been created.

Step 3

Now, select Storage option from the left menu of the Firebase project and get started with Storage.

Step 4

Change the security rules for storage. For that go to the Rules tab and place the below code.

Note Here, you can define your security rules to restrict unauthorized access.

rules_version = '2';    
service firebase.storage {    
  match /b/{bucket}/o {    
    match /{allPaths=**} {    
      allow read, write;    
    }    
  }    
}

Step 5

I have created 2 folders, chats and profiles. Chats will store chat related images and profiles will store a profile image of the user. Please check the below screenshot.

Step 6

Great. We are all done with Firebase Project Setup. Now we will move to programming path.

Programming Steps

Step 1

As we have created a project in the first step of Firebase Project Setup, we need to add the dependency to select an image from the device and upload to firebase storage. For that open pubspec.yaml file in the root of the project and add dependency like below.

dependencies:    
 flutter:    
   sdk: flutter    
 cupertino_icons: ^0.1.2    
 image_picker: ^0.6.0+17    
 firebase_storage: ^3.0.3 

Note Run Flutter packages that you can get in terminal OR If you are using Visual Studio Code then after saving the file it will automatically run the Flutter packages get command.

Step 2

Now, open main.dart file under lib folder. This is the entry point of the app.

Step 3

Import the following packages for choosing image and uploading image file to firebase storage.

    import 'dart:io';    
    import 'package:firebase_storage/firebase_storage.dart'; // For File Upload To Firestore    
    import 'package:flutter/material.dart';    
    import 'package:image_picker/image_picker.dart'; // For Image Picker    
    import 'package:path/path.dart' as Path;  

Step 4

Define the state variable in state class. _image variable stores the file which is selected using file picker and uploadedFileURL will stores the uploaded file url.

File _image;    
String _uploadedFileURL;

Step 5

Create an architecture for the sample project. Following is the build method which implements the architecture.


    @override    
     Widget build(BuildContext context) {    
       return Scaffold(    
         appBar: AppBar(    
           title: Text('Firestore File Upload'),    
         ),    
         body: Center(    
           child: Column(    
             children: <Widget>[    
               Text('Selected Image'),    
               _image != null    
                   ? Image.asset(    
                       _image.path,    
                       height: 150,    
                     )    
                   : Container(height: 150),    
               _image == null    
                   ? RaisedButton(    
                       child: Text('Choose File'),    
                       onPressed: chooseFile,    
                       color: Colors.cyan,    
                     )    
                   : Container(),    
               _image != null    
                   ? RaisedButton(    
                       child: Text('Upload File'),    
                       onPressed: uploadFile,    
                       color: Colors.cyan,    
                     )    
                   : Container(),    
               _image != null    
                   ? RaisedButton(    
                       child: Text('Clear Selection'),    
                       onPressed: clearSelection,    
                     )    
                   : Container(),    
               Text('Uploaded Image'),    
               _uploadedFileURL != null    
                   ? Image.network(    
                       _uploadedFileURL,    
                       height: 150,    
                     )    
                   : Container(),    
             ],    
           ),    
         ),    
       );  

Step 6

chooseFile() will ask the user for access to the media file permission and if the user allows it, then choose the image from the image gallery.

Future chooseFile() async {    
   await ImagePicker.pickImage(source: ImageSource.gallery).then((image) {    
     setState(() {    
       _image = image;    
     });    
   });    
 } 

Step 7

uploadFile() will upload the chosen file to the Google Firebase Firestore in the chats folder and return the uploaded file URL.

Future uploadFile() async {    
   StorageReference storageReference = FirebaseStorage.instance    
       .ref()    
       .child('chats/${Path.basename(_image.path)}}');    
   StorageUploadTask uploadTask = storageReference.putFile(_image);    
   await uploadTask.onComplete;    
   print('File Uploaded');    
   storageReference.getDownloadURL().then((fileURL) {    
     setState(() {    
       _uploadedFileURL = fileURL;    
     });    
   });    
 } 

Step 8

Congratulations, you are all done with File Upload to Firebase Storage with Flutter. For Full source code check out my attached source file.

NOTE PLEASE CHECK OUT GIT REPO FOR FULL SOURCE CODE. YOU NEED TO ADD YOUR google-services.json FILE IN ANDROID => APP FOLDER.

MAY BE ERRORS:Error: import androidx.annotation.NonNull;

SOLUTION

Add the below lines in android/gradle.properties file,

android.useAndroidX=true
android.enableJetifier=true

Conclusion

In this article, we have learned how to upload files to Google Firebase Storage using Flutter. In this article, we have uploaded image files but you can also upload audio, video, doc, pdfs, etc.

#firebase #flutter #mobile-apps

Upload Image File to Firebase Storage using Flutter
27.15 GEEK