Upload Image File To Firebase Storage Using Flutter

In this article, we will learn how to upload an image to Firebase storage using Flutter.

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 blog, 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 (<project>/build.gradle): means build.gradle file in Android folder directly,
  1. buildscript {    
  2.  dependencies {    
  3.  // Add this line    
  4.  classpath 'com.google.gms:google-services:4.2.0'    
  5.  }    
  6. }  
App-level build.gradle (<project>/<app-module>/build.gradle): means build.gradle file in Android = > App folder
  1. // Add to the bottom of the file    
  2. 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. 
  1. rules_version = '2';    
  2. service firebase.storage {    
  3.   match /b/{bucket}/o {    
  4.     match /{allPaths=**} {    
  5.       allow read, write;    
  6.     }    
  7.   }    
  8. }    
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.
  1. dependencies:    
  2.  flutter:    
  3.    sdk: flutter    
  4.  cupertino_icons: ^0.1.2    
  5.  image_picker: ^0.6.0+17    
  6.  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.
  1. import 'dart:io';    
  2. import 'package:firebase_storage/firebase_storage.dart'// For File Upload To Firestore    
  3. import 'package:flutter/material.dart';    
  4. import 'package:image_picker/image_picker.dart'// For Image Picker    
  5. 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.
  1. File _image;    
  2. String _uploadedFileURL;   
Step 5
 
Create an architecture for the sample project. Following is the build method which implements the architecture.
  1. @override    
  2.  Widget build(BuildContext context) {    
  3.    return Scaffold(    
  4.      appBar: AppBar(    
  5.        title: Text('Firestore File Upload'),    
  6.      ),    
  7.      body: Center(    
  8.        child: Column(    
  9.          children: <Widget>[    
  10.            Text('Selected Image'),    
  11.            _image != null    
  12.                ? Image.asset(    
  13.                    _image.path,    
  14.                    height: 150,    
  15.                  )    
  16.                : Container(height: 150),    
  17.            _image == null    
  18.                ? RaisedButton(    
  19.                    child: Text('Choose File'),    
  20.                    onPressed: chooseFile,    
  21.                    color: Colors.cyan,    
  22.                  )    
  23.                : Container(),    
  24.            _image != null    
  25.                ? RaisedButton(    
  26.                    child: Text('Upload File'),    
  27.                    onPressed: uploadFile,    
  28.                    color: Colors.cyan,    
  29.                  )    
  30.                : Container(),    
  31.            _image != null    
  32.                ? RaisedButton(    
  33.                    child: Text('Clear Selection'),    
  34.                    onPressed: clearSelection,    
  35.                  )    
  36.                : Container(),    
  37.            Text('Uploaded Image'),    
  38.            _uploadedFileURL != null    
  39.                ? Image.network(    
  40.                    _uploadedFileURL,    
  41.                    height: 150,    
  42.                  )    
  43.                : Container(),    
  44.          ],    
  45.        ),    
  46.      ),    
  47.    );  
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. 
  1. Future chooseFile() async {    
  2.    await ImagePicker.pickImage(source: ImageSource.gallery).then((image) {    
  3.      setState(() {    
  4.        _image = image;    
  5.      });    
  6.    });    
  7.  }  
Step 7
 
uploadFile() will upload the chosen file to the Google Firebase Firestore in the chats folder and return the uploaded file URL. 
  1. Future uploadFile() async {    
  2.    StorageReference storageReference = FirebaseStorage.instance    
  3.        .ref()    
  4.        .child('chats/${Path.basename(_image.path)}}');    
  5.    StorageUploadTask uploadTask = storageReference.putFile(_image);    
  6.    await uploadTask.onComplete;    
  7.    print('File Uploaded');    
  8.    storageReference.getDownloadURL().then((fileURL) {    
  9.      setState(() {    
  10.        _uploadedFileURL = fileURL;    
  11.      });    
  12.    });    
  13.  }  
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.