Mega Bundle SALE is ON! Get ALL of our amazing Flutter codebases with 95% OFF discount 🔥

In this article, we are going to build a simple functionality to showcase how you can upload photos to Firebase Storage in Flutter apps. We’ll be focusing on both the UI and the code functionality.

As a starting point, I’d want to design a basic interface that has an image container and an upload button. Images are immediately uploaded to Firebase Storage and presented on the screen after being picked up manually by the user.

flutter firebase storage photos

In case you are not familiar with Firebase Storage, you can learn more about it on the official documentation. In short, Firebase Storage is Google’s Cloud version of AWS S3.

To upload photos, videos, audio, or document files to Firebase Storage in Flutter and Dart, simply follow our short tutorial below. You can also skip everything and just download the code, in case you already have a lot of experience with Flutter development.

Installing the Flutter Dependencies

We’ll need a few Dart library packages to make use of Firebase services and get access to the device gallery. The following lines of code provide a list of the plugins that should be used.

The following are the available plugins, so please add them to your app as dependencies in the .yaml file:

firebase_core: ^0.4.5
image_picker: ^0.6.7+14
firebase_storage: ^3.1.6
permission_handler: ^5.0.1+1

A fundamental Firebase package, Firebase Core enables us to utilize the service modules in our Flutter apps.

image_picker: Modules may choose a picture from the device gallery using this package.

firebase_storage: Firebase Storage service components for Flutter are included in this package. We’ll be able to customize the uploading process using the APIs in this library.

permission_handler: We may manage access to our store using the permission handler package. It offers a simple user interface for managing access to the permissions of a user’s device.

To install these plugins, we need to copy them and put them into the pubspec.yaml file, and save it. To install them, use the following command in a shell:

flutter get packages

Importing packages to the main.dart file may be done after the installation as seen in the code snippet below:

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

Building the Main App Screen

The following code excerpt shows how to construct a new stateful widget class named ImageUpload in the main.dart file:

class ImageUpload extends StatefulWidget {
  @override
  _ImageUploadState createState() => _ImageUploadState();
}

class _ImageUploadState extends State<ImageUpload> {
  String imageUrl;

  @override
  Widget build(BuildContext context) {
    backgroundColor: Colors.white,
    return Scaffold(  
      appBar: AppBar(
        title: Text('Upload Image', style: TextStyle(color: Colors.black87, fontWeight: FontWeight.bold),),
        centerTitle: true,
        elevation: 0.0,
        backgroundColor: Colors.white,
      ),
      body: Container()
   );
  }
}

A Scaffold widget with an AppBar and an empty Container was provided as a body property in the widget building method.

MyApp stateless class object must now be called as seen below:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ImageUpload(),
    );
  }
}

Adding an Image Placeholder to the UI

In the body part of the Scaffold, we will add an Image Placeholder section that displays the picture after the upload gets done and a button that will take us to the device gallery and let us to upload the image.

Code for the Image Placeholder section is presented in the following manner:

body: Container(
        color: Colors.white,
        child: Column(  
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(15),
              padding: EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(
                  Radius.circular(15),
                ),
                border: Border.all(color: Colors.white),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black12,
                    offset: Offset(2, 2),
                    spreadRadius: 2,
                    blurRadius: 1,
                  ),
                ],
              ),
              child: (imageUrl != null)
                ? Image.network(imageUrl)
                : Image.network('https://i.imgur.com/sUFH1Aq.png')
            ),
          ],
        ),
      ),

Here, we have rendered a placeholder image using the Image.network widget, but in your case, an actual imageUrl will be available after the upload.

How to Add a Raised Button

Using the RaisedButton widget, we’ll create a basic button underneath the Image Placeholder area. A SizedBox widget separates the placeholder from the button. The code from the following code snippet should be placed directly below the Container widget that houses the Image Placeholder section:

SizedBox(height: 20.0,),
RaisedButton(
  child: Text("Upload Image", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20)),
  onPressed: (){},
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(18.0),
    side: BorderSide(color: Colors.blue)
  ),
  elevation: 5.0,
  color: Colors.blue,
  textColor: Colors.white,
  padding: EdgeInsets.fromLTRB(15, 15, 15, 15),
  splashColor: Colors.grey,
),

We need to create the upload method from scratch since it isn’t yet implemented in the button code.

Uploading the Images to Firebase Storage in Flutter

When you pick a picture from the gallery, you’ll be able to upload it to Firebase Storage and see it in the Image Placeholder section when the upload is complete.

The first step is to set up a few plugins, as seen in the code snippet:

uploadImage() async {
    final _firebaseStorage = FirebaseStorage.instance;
    final _imagePicker = ImagePicker();
    PickedFile image;
}

Then, we need to request access to the device gallery using the permission plugin’s request function. The permissionStatus variable will be used to keep track of the user’s permissions, as seen in the following code snippet:

await Permission.photos.request();
var permissionStatus = await Permission.photos.status;

After that, we’ll need to see whether the permission is granted and then choose a picture from the gallery. The path file must be obtained.

We may upload an image to Firebase Storage by using the putFile function in the firebaseStorage package module. Firebase storage will be able to access images that are stored in the child method’s path and alias. The following code sample shows how to use the upload method in its entirety:

uploadImage() async {
    final _firebaseStorage = FirebaseStorage.instance;
    final _imagePicker = ImagePicker();
    PickedFile image;
    //Check Permissions
    await Permission.photos.request();

    var permissionStatus = await Permission.photos.status;

    if (permissionStatus.isGranted){
      //Select Image
      image = await _imagePicker.getImage(source: ImageSource.gallery);
      var file = File(image.path);

      if (image != null){
        //Upload to Firebase
        var snapshot = await _firebaseStorage.ref()
        .child('images/imageName')
        .putFile(file).onComplete;
        var downloadUrl = await snapshot.ref.getDownloadURL();
        setState(() {
          imageUrl = downloadUrl;
        });
      } else {
        print('No Image Path Received');
      }
    } else {
      print('Permission not granted. Try Again with permission access');
    }
  }

On the RaisedButton widget’s onPressed functional property, we just need to run the uploadImage function:

RaisedButton(
    child: Text("Upload Image", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20)),
    onPressed: (){
      uploadImage();
    },

This is what we came up with as a final outcome:

 

It’s important to keep in mind that depending on the size of your picture file, uploading it to Firebase Storage may take some time. It appears in the Image Placeholder area when the upload is complete.

Image uploaded to Firebase Storage may be seen in the Firebase Storage console as illustrated in the following image:

Using a Flutter app, we were able to successfully upload the picture to Firebase Storage.

Conclusion

I hope this detailed tutorial will help you develop a comparable feature for your Flutter project. Images are not the only things that may benefit from this technique; other types of data files such as videos or audio files can also be uploaded in this manner. Make certain to give it a go. As you can see, Flutter makes uploading photos and videos to Firebase Storage pretty straightforward.


Leave a Reply

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

Shopping Cart