Upload Image to Firebase Storage - Flutter (Android & Ios)

Last updated Aug 28, 2021

In this post, we are going to learn how to upload images to Firebase storage in Flutter.

We can pick Image from Gallery or Capture image from Camera and upload it into Firebase.

 

Image Upload to Firebase storage

 

 

Download Source code

 

 

Let's get started

Step 1: Create a Flutter application

Step 2: Configure Firebase application 

Check the previous post how to configure Flutter application with Firebase

 

Step 3: Add require dependencies in pubspec.yaml file

dependencies:
  firebase_storage: ^10.0.3
  firebase_core: ^1.6.0
  firebase_analytics: ^8.3.1
  image_picker: ^0.8.3+3

 

Step 4:

How to pick Image from Camera or Gallery, Check the previous tutorial

 

final picker = ImagePicker();

Future pickImage() async {
  final pickedFile = await picker.getImage(source: ImageSource.camera);

  setState(() {
    _imageFile = File(pickedFile!.path);
  });
}

 

Step 5: Uploading Image to FirebaseStorage

 

Once an image is selected using ImagePicker, it will be displayed in the screen. Clicking on 'Upload Image' button on screen will upload the image to Firebase Storage. Make sure that FirebaseStorage write rules are configured appropriately. I'm temporarily enabling write access on FirebaseStorage access using allow write: if true;. Make sure to disable it once you've confirmed the functionality. 

The following code will take the image file on device and upload it to the uploads folder in the FirebaseStorage

 

Future uploadImageToFirebase(BuildContext context) async {
  String fileName = basename(_imageFile!.path);
  firebase_storage.Reference ref =
  firebase_storage.FirebaseStorage.instance
      .ref().child('uploads').child('/$fileName');

  final metadata = firebase_storage.SettableMetadata(
      contentType: 'image/jpeg',
      customMetadata: {'picked-file-path': fileName});
  firebase_storage.UploadTask uploadTask;
  //late StorageUploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
  uploadTask = ref.putFile(io.File(_imageFile!.path)!, metadata);

  firebase_storage.UploadTask task= await Future.value(uploadTask);
  Future.value(uploadTask).then((value) => {
  print("Upload file path ${value.ref.fullPath}")
  }).onError((error, stackTrace) => {
    print("Upload file path error ${error.toString()} ")
  });



}

 

Step 5: Run application

 

Flutter PickImage

 

 

Firebase Upload Image

 

iOS configuration

Add permissions in iOS Info.list

NSCameraUsageDescription
Need to access your camera to capture a photo add and update profile picture.

NSPhotoLibraryUsageDescription
Need to access your photo library to select a photo add and update profile picture

 

Complete main.dart file

import 'dart:io';
import 'dart:io' as io;
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_core/firebase_core.dart' as firebase_core;
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:path/path.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await firebase_core.Firebase.initializeApp();
  runApp(MaterialApp(
    title: 'Firebase Storage Demo',
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: UploadingImageToFirebaseStorage(),
  ));
}

final Color green = Colors.brown;
final Color orange = Colors.brown;

class UploadingImageToFirebaseStorage extends StatefulWidget {
  @override
  _UploadingImageToFirebaseStorageState createState() =>
      _UploadingImageToFirebaseStorageState();
}

class _UploadingImageToFirebaseStorageState
    extends State {
   File? _imageFile=null;

  ///NOTE: Only supported on Android & iOS
  ///Needs image_picker plugin {https://pub.dev/packages/image_picker}
  final picker = ImagePicker();

  Future pickImage() async {
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    setState(() {
      _imageFile = File(pickedFile!.path);
    });
  }

  Future uploadImageToFirebase(BuildContext context) async {
    String fileName = basename(_imageFile!.path);
    firebase_storage.Reference ref =
    firebase_storage.FirebaseStorage.instance
        .ref().child('uploads').child('/$fileName');

    final metadata = firebase_storage.SettableMetadata(
        contentType: 'image/jpeg',
        customMetadata: {'picked-file-path': fileName});
    firebase_storage.UploadTask uploadTask;
    //late StorageUploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
    uploadTask = ref.putFile(io.File(_imageFile!.path)!, metadata);

    firebase_storage.UploadTask task= await Future.value(uploadTask);
    Future.value(uploadTask).then((value) => {
    print("Upload file path ${value.ref.fullPath}")
    }).onError((error, stackTrace) => {
      print("Upload file path error ${error.toString()} ")
    });



  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          Container(
            height: 360,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(250.0),
                    bottomRight: Radius.circular(10.0)),
                gradient: LinearGradient(
                    colors: [green,orange],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight)),
          ),
          Container(
            margin: const EdgeInsets.only(top: 80),
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Center(
                    child: Text(
                      "Uploading Image to Firebase Storage",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: 28,
                          fontStyle: FontStyle.italic),
                    ),
                  ),
                ),
                SizedBox(height: 20.0),
                Expanded(
                  child: Stack(
                    children: [
                      Container(
                        height: double.infinity,
                        margin: const EdgeInsets.only(
                            left: 30.0, right: 30.0, top: 10.0),
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(30.0),
                          child: _imageFile != null
                              ? Image.file(_imageFile!)
                              : FlatButton(
                            child: Icon(
                              Icons.add_a_photo,
                              color: Colors.blue,
                              size: 50,
                            ),
                            onPressed: pickImage,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                uploadImageButton(context),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget uploadImageButton(BuildContext context) {
    return Container(
      child: Stack(
        children: [
          Container(
            padding:
            const EdgeInsets.symmetric(vertical: 5.0, horizontal: 16.0),
            margin: const EdgeInsets.only(
                top: 30, left: 20.0, right: 20.0, bottom: 20.0),
            decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [orange, green],
                ),
                borderRadius: BorderRadius.circular(30.0)),
            child: FlatButton(
              onPressed: () => uploadImageToFirebase(context),
              child: Text(
                "Upload Image",
                style: TextStyle(fontSize: 20,color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
/*
if request.auth != null*/

 

Conclusion: In this flutter application we covered how to upload image to firestore.

Tags: Firebase Integration, Firebase Authentication, Upload Image To Firebase, PickImage

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

11034 Views