How to Upload Image to Firebase Storage In Flutter

How to Upload Image to Firebase Storage In Flutter ?

Earlier we have been through Step By Step Guide to Implement Firebase with Flutter. When we use Firebase to store data from Application. So in this article, We will go through How to Upload Image to Firebase Storage In Flutter?

How to Upload Image to Firebase Storage In Flutter?

When you select an image with the image picker, it returns a File, you can use await to wait until the user selects a file then store it as a File. Here is some sample code of how you can get the file from the image picker and upload it to Firebase. Here is a sample code that takes an image from a gallery or camera and uploads it on Firebase Storage.

FirebaseStorage _storage = FirebaseStorage.instance;

   Future<Uri> uploadPic() async {

   //Get the file from the image picker and store it 
   File image = await ImagePicker.pickImage(source: ImageSource.gallery);  

   //Create a reference to the location you want to upload to in firebase  
   StorageReference reference = _storage.ref().child("images/");

   //Upload the file to firebase 
   StorageUploadTask uploadTask = reference.putFile(file);

   // Waits till the file is uploaded then stores the download url 
   Uri location = (await uploadTask.future).downloadUrl;

   //returns the download url 
   return location;
  }

Add below dependencies in your pubspec.yaml in your project files.

dependencies:
  flutter:
    sdk: flutter
 
  firebase_storage: 4.0.0
  image_picker: ^0.6.7+12

Consider a code snippet like the below:

//Creating a global Variable    
StorageReference storageReference = FirebaseStorage.instance.ref();
File _image;

void getImage(){
    _image = await ImagePicker.pickImage(source: ImageSource.gallery); 
}

void addImageToFirebase(){
    //CreateRefernce to path.
    StorageReference ref = storageReference.child("yourstorageLocation/");

    //StorageUpload task is used to put the data you want in storage
    //Make sure to get the image first before calling this method otherwise _image will be null.

    StorageUploadTask storageUploadTask = ref.child("image1.jpg").putFile(_image);

     if (storageUploadTask.isSuccessful || storageUploadTask.isComplete) {
          final String url = await ref.getDownloadURL();
          print("The download URL is " + url);
     } else if (storageUploadTask.isInProgress) {

          storageUploadTask.events.listen((event) {
          double percentage = 100 *(event.snapshot.bytesTransferred.toDouble() 
                               / event.snapshot.totalByteCount.toDouble());  
          print("THe percentage " + percentage.toString());
          });

          StorageTaskSnapshot storageTaskSnapshot =await storageUploadTask.onComplete;
          downloadUrl1 = await storageTaskSnapshot.ref.getDownloadURL();

          //Here you can get the download URL when the task has been completed.
          print("Download URL " + downloadUrl1.toString());

     } else{
          //Catch any cases here that might come up like canceled, interrupted 
     }

}

We can also create a custom function like the below:

Future uploadPic(File image) async {
  setState(() {
    uploadingImage = true;
  });
  StorageReference storageReference =
      FirebaseStorage.instance.ref().child(Path.basename(image.path));
  StorageUploadTask uploadTask = storageReference.putFile(image);
  await uploadTask.onComplete.then((taskSnapshot) async {
    _uploadedFileURL = await taskSnapshot.ref.getDownloadURL();
    _showSnackBar("Successfully uploaded profile picture");
  }).catchError((e) {
    _showSnackBar("Failed to upload profile picture");
  });
  setState(() {
    uploadingImage = false;
  });
}

We need to import all the required and  necessary packages like the below:

import 'package:path/path.dart' as Path; 
import 'package:firebase_storage/firebase_storage.dart';
import 'package:image_picker/image_picker.dart';

User can also give a try to below plugin firebase_picture_uploader

Conclusion:

In this article, we have been through How to Upload Image to Firebase Storage In Flutter?

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number