ZXERSTON
ZXERSTON

Reputation: 323

How to download file from firebase to local phone storage in flutter?

I am new to flutter and I am clueless on how to implement a function to download a PDF file from firebase. I went through multiple tutorials regarding downloading files from cloud storage to local storage in flutter app and still unable to make it work.

I want when user presses the button

 onPressed: () async {},

Then, it will straight away download the file from my firebase cloud storage to their local files.

I know I have to use writeToFile, but how do I implement the function?

Hope you can help me, thanks!

Upvotes: 3

Views: 5766

Answers (1)

JoakimMellonn
JoakimMellonn

Reputation: 160

When looking at the docs for Firebase Cloud Storage, you can download a file from the Cloud Storage to the local documents folder, by using the following function:

//You'll need the Path provider package to get the local documents folder.
import 'package:path_provider/path_provider.dart';

Future<void> downloadFileExample() async {
  //First you get the documents folder location on the device...
  Directory appDocDir = await getApplicationDocumentsDirectory();
  //Here you'll specify the file it should be saved as
  File downloadToFile = File('${appDocDir.path}/downloaded-pdf.pdf');
  //Here you'll specify the file it should download from Cloud Storage
  String fileToDownload = 'uploads/uploaded-pdf.pdf';

  //Now you can try to download the specified file, and write it to the downloadToFile.
  try {
    await firebase_storage.FirebaseStorage.instance
        .ref(fileToDownload)
        .writeToFile(downloadToFile);
  } on firebase_core.FirebaseException catch (e) {
    // e.g, e.code == 'canceled'
    print('Download error: $e');
  }
}

You can find this, and read more about it on this page: https://firebase.flutter.dev/docs/storage/usage

To implement it on the onPressed funtion, i would suggest having the function in the same class as you have the button, and executing the function from the onPressed like this:

onPressed: () {
  downloadFileExample();
}

Upvotes: 6

Related Questions