Hey Flutter devs!
Want to grab a file from Firebase Storage and show your users how the download is going? This quick guide shows you a neat way to do it.
Getting Started
First things first, you need to make sure your app has permission to save files on the device. We use the permission_handler
plugin for this. Always ask the user nicely!
if (await Permission.storage.request().isDenied) {
throw "Vous devez accepter la permission d'écrire";
}
This code checks if storage permission is denied and throws an error if it is, reminding the user to grant it.
Finding the File on Firebase
Next, we get a reference to the file you want to download using its path in Firebase Storage.
var fileRef = storage.ref().child(path);
var fileName = fileRef.name;
This gets the file reference and its name, which we'll need later.
Where to Save the File?
We need a spot on the device to save the downloaded file. The code picks a directory based on the platform.
Android Specifics
On Android, it defaults to the common Download folder.
Directory directory;
if (Platform.isAndroid) {
directory = Directory("/storage/emulated/0/Download");
} else {
directory = (await getExternalStorageDirectory())!;
}
For other platforms, it uses the external storage directory provided by a helper function.
Preparing the Destination
We build the full path for the final file and make sure the directory exists.
final File destinationFile = File('${directory.path}/$fileName');
Handling Existing Files
What if a file with the same name is already there? This code snippet deletes the old one before saving the new one. You might want to handle this differently depending on your app's needs.
if (destinationFile.existsSync()) {
destinationFile.deleteSync();
}
destinationFile.createSync();
Starting the Download and Tracking Progress
Now, the fun part! We start the download using writeToFile
on the Firebase storage reference.
var task = fileRef.writeToFile(destinationFile);
yield* task.asStream();
The yield*
keyword combined with task.asStream()
is super useful here. It turns the download task into a Stream
. This means you can listen to this stream and get updates on the download progress as it happens.
Calculating Progress
To show how much of the file has been downloaded, you can use the information from the stream updates:
var progress = task.bytesTransferred / task.totalBytes * 100;
This gives you the percentage of the download completed.
And that's it! You can now download files from Firebase Storage and easily display the download progress in your Flutter app.