Flutter Firebase Storage Examples
Flutter Firebase Storage - How To Examples
Introduction
Firebase Storage is a powerful cloud storage solution provided by Firebase, which allows you to store and retrieve user-generated content such as images, videos, and audio files. In this tutorial, we will explore various examples to demonstrate how to use Firebase Storage in Flutter applications.
Prerequisites
To follow along with this tutorial, you need to have the following:
- Flutter SDK installed on your machine
- A Firebase project created on the Firebase console
- FlutterFire dependency added to your Flutter project
Installation
To use Firebase Storage in your Flutter application, you need to add the firebase_storage
package as a dependency in your pubspec.yaml
file:
dependencies:
flutter:
sdk: flutter
firebase_storage: ^5.0.0
After adding the dependency, run the following command to fetch the package:
flutter pub get
Now you are ready to use Firebase Storage in your Flutter application.
Example 1: Uploading a File to Firebase Storage
In this example, we will demonstrate how to upload a file to Firebase Storage.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';
Future<void> uploadFile(File file) async {
String fileName = basename(file.path);
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = storageReference.putFile(file);
await uploadTask.whenComplete(() => print('File uploaded successfully'));
}
Expected Output: The file will be uploaded to the specified path in Firebase Storage, and the success message will be printed.
Example 2: Downloading a File from Firebase Storage
In this example, we will demonstrate how to download a file from Firebase Storage.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path_provider/path_provider.dart';
Future<void> downloadFile(String fileName) async {
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String filePath = '${appDocumentsDirectory.path}/$fileName';
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
File file = File(filePath);
await storageReference.writeToFile(file);
print('File downloaded successfully');
}
Expected Output: The specified file will be downloaded from Firebase Storage and saved to the device's application documents directory. The success message will be printed.
Example 3: Deleting a File from Firebase Storage
In this example, we will demonstrate how to delete a file from Firebase Storage.
import 'package:firebase_storage/firebase_storage.dart';
Future<void> deleteFile(String fileName) async {
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
await storageReference.delete();
print('File deleted successfully');
}
Expected Output: The specified file will be deleted from Firebase Storage, and the success message will be printed.
Example 4: Getting Download URL of a File in Firebase Storage
In this example, we will demonstrate how to get the download URL of a file stored in Firebase Storage.
import 'package:firebase_storage/firebase_storage.dart';
Future<String> getDownloadURL(String fileName) async {
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
String downloadURL = await storageReference.getDownloadURL();
return downloadURL;
}
Expected Output: The download URL of the specified file in Firebase Storage will be returned.
Example 5: Monitoring File Upload Progress
In this example, we will demonstrate how to monitor the upload progress of a file to Firebase Storage.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';
void uploadFileWithProgress(File file) {
String fileName = basename(file.path);
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = storageReference.putFile(file);
uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
double progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
print('Upload progress: $progress%');
}, onError: (Object e) {
print('Upload failed: $e');
}, onDone: () {
print('File uploaded successfully');
});
}
Expected Output: The upload progress in percentage will be printed, and once the upload is complete, the success message will be printed.
Example 6: Pausing and Resuming File Upload
In this example, we will demonstrate how to pause and resume the upload of a file to Firebase Storage.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';
void uploadFileWithPauseResume(File file) {
String fileName = basename(file.path);
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
UploadTask uploadTask = storageReference.putFile(file);
uploadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
double progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
print('Upload progress: $progress%');
}, onError: (Object e) {
print('Upload failed: $e');
}, onDone: () {
print('File uploaded successfully');
});
// Pause the upload
uploadTask.pause();
// Resume the upload
uploadTask.resume();
}
Expected Output: The upload progress in percentage will be printed. The upload can be paused and resumed using the provided methods.
Example 7: Setting Metadata for Uploaded Files
In this example, we will demonstrate how to set metadata for files uploaded to Firebase Storage.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';
Future<void> uploadFileWithMetadata(File file) async {
String fileName = basename(file.path);
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
SettableMetadata metadata = SettableMetadata(
contentType: 'image/jpeg',
customMetadata: {'user': 'John Doe'},
);
UploadTask uploadTask = storageReference.putFile(file, metadata);
await uploadTask.whenComplete(() => print('File uploaded successfully with metadata'));
}
Expected Output: The file will be uploaded to Firebase Storage with the specified metadata, and the success message will be printed.
Example 8: Listing Files in a Firebase Storage Directory
In this example, we will demonstrate how to list all the files in a specific directory in Firebase Storage.
import 'package:firebase_storage/firebase_storage.dart';
Future<List<String>> listFilesInDirectory(String directory) async {
ListResult listResult = await FirebaseStorage.instance.ref().child(directory).listAll();
List<String> fileNames = listResult.items.map((item) => item.name).toList();
return fileNames;
}
Expected Output: A list of file names in the specified directory in Firebase Storage will be returned.
Example 9: Monitoring File Download Progress
In this example, we will demonstrate how to monitor the download progress of a file from Firebase Storage.
import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path_provider/path_provider.dart';
void downloadFileWithProgress(String fileName) {
Directory appDocumentsDirectory = await getApplicationDocumentsDirectory();
String filePath = '${appDocumentsDirectory.path}/$fileName';
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
File file = File(filePath);
DownloadTask downloadTask = storageReference.writeToFile(file);
downloadTask.snapshotEvents.listen((TaskSnapshot snapshot) {
double progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
print('Download progress: $progress%');
}, onError: (Object e) {
print('Download failed: $e');
}, onDone: () {
print('File downloaded successfully');
});
}
Expected Output: The download progress in percentage will be printed, and once the download is complete, the success message will be printed.
Example 10: Resizing Images before Uploading to Firebase Storage
In this example, we will demonstrate how to resize images before uploading them to Firebase Storage.
import 'dart:io';
import 'package:image/image.dart' as img;
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';
Future<void> uploadResizedImage(File file) async {
String fileName = basename(file.path);
Reference storageReference = FirebaseStorage.instance.ref().child('uploads/$fileName');
// Read the image file
List<int> imageBytes = await file.readAsBytes();
// Resize the image to 500x500 pixels
img.Image image = img.decodeImage(imageBytes);
img.Image resizedImage = img.copyResize(image, width: 500, height: 500);
List<int> resizedImageBytes = img.encodeJpg(resizedImage);
UploadTask uploadTask = storageReference.putData(resizedImageBytes);
await uploadTask.whenComplete(() => print('Resized image uploaded successfully'));
}
Expected Output: The image will be resized to 500x500 pixels before uploading it to Firebase Storage, and the success message will be printed.
Conclusion
In this tutorial, we covered various examples to demonstrate how to use Firebase Storage in Flutter applications. You can now leverage the power of Firebase Storage to store and retrieve user-generated content in your Flutter projects.