Flutter Image Upload

Srivats Venkataraman
4 min readMay 6, 2021

--

There are a lot of tutorials on how to upload images to Firebase Cloud Storage. One constant theme that I have seen in these tutorials is the use of the “dart:html” package. Making use of this package will cause rendering issues when you run the app on mobile. So I decided to share a different way of uploading images that is safe on all platforms.

Background

In order to follow this tutorial, basic knowledge of Flutter and Dart is required. Knowledge of how to set up a Flutter project with Firebase, and enable web support.

Packages

For Image Upload we are going to make use of the following packages:

Lets Code

All the code for this can be done in one file. Let’s create a file called “image_upload.dart”. Once that is done, import the following files:

import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:universal_platform/universal_platform.dart';
import 'package:image_picker/image_picker.dart';

Now that we have our imports in place, let’s create a void method called imgUpload make sure this method is an async method. This method can be called anything you like. Inside this method, we are going to do two things. 1) allow the user to choose an image to upload. 2) write our logic to upload the selected file. Here is the code you can copy and paste if you like or type it out:

// create a file variable and a string variable
File _image;
String photoUrl;
void imgUpload() async {
if (UniversalPlatform.isWeb) {
// initialize the file picker library
FilePickerResult result = await FilePicker.platform.pickFiles();
// assign the result to a PlatformFile type
PlatformFile file = result.files.first;
// create our meta data information
final metadata = firebase_storage.SettableMetadata(
contentType: 'image/${file.extension}',
);
// path to where we want out file to be saved
firebase_storage.Reference ref = firebase_storage.FirebaseStorage.instance
.ref()
.child('pictures')
.child('/');
firebase_storage.UploadTask task;
task = ref.putData(file.bytes, metadata);
}
if (UniversalPlatform.isAndroid) {
// get image using image picker
final pickedFile =
await ImagePicker().getImage(source: ImageSource.gallery);
setState(() {
_image = File(pickedFile.path);
});
firebase_storage.Reference ref =
firebase_storage.FirebaseStorage.instance.ref().child("pictures/");
firebase_storage.UploadTask task = ref.putFile(_image);
task.storage.ref().getDownloadURL().then((value) => {
photoUrl = value.toString(),
});
}
}

If you looked at the packages you might see that image_picker is compatible with the web, but we are not using it? Let me explain, you are right we can use it. But when the file is uploaded it will be uploaded as a stream, and since there is no way of figuring out the extension using image_picker, we make use of the FilePicker instead. If your wondering why the extension is not available here is a short summary. When we pick an image on the web using the image_picker library it is temporarily saved in the browser's local memory and hence when we try accessing it we will get something like “localhost:8080//random-string”.

Now if your thinking well file_picker is also compatible with mobile and still I choose imgage_picker? Well, I wanted to show how both can be used hence why I choose image_picker for mobile.

Our method is set up, now we need to call it. This will be done in our main method. We are going to create a GestureDetector widget and the child is going to be a Container. In this container, we are going to show the text choose image. We won’t update the content of the container once the image is uploaded, that will be a separate tutorial. Once again you can copy the code from below, or type it out:

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: GestureDetector(
onTap: () {
imgDetail();
},
child: Center(
child: Container(
height: 200,
width: 200,
decoration: BoxDecoration(
border: Border.all(
width: 2,
),
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text("Choose Photo"),
),
),
),
),
),
);
}

Now that the code is set up, you can run it on any platform of choice and check your Firebase Storage tab and you will see the image uploaded there.

Here is the full gist:

Hoped you enjoyed this article and learned how to upload images to Cloud Storage using both mobile and web. Do leave a like and maybe even a follow so you see when the next article is published.

Follow me on social media:

Instagram: instagram.com/srivats_22/
LinkedIn: linkedin.com/in/srivatsvenk/
Portfolio: srivats-22.web.app/

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Srivats Venkataraman
Srivats Venkataraman

Written by Srivats Venkataraman

Hello, I am Srivats Venkataraman. Computer Science major. I love flutter development, and want to write and post videos tutorials on flutter development.

Responses (1)

Write a response