如何在flutter中将文件从firebase下载到本地手机存储?

ZXE*_*TON 2 cloud-storage firebase flutter

我是 flutter 新手,对如何实现从 firebase 下载 PDF 文件的功能一无所知。我浏览了多个关于在 flutter 应用程序中将文件从云存储下载到本地存储的教程,但仍然无法使其工作。

我想要当用户按下按钮时

 onPressed: () async {},
Run Code Online (Sandbox Code Playgroud)

然后,它会立即将文件从我的 firebase 云存储下载到本地文件。

我知道我必须使用 writeToFile,但是我如何实现该功能?

希望你能帮助我,谢谢!

Joa*_*onn 5

查看 Firebase Cloud Storage 的文档时,您可以使用以下函数将文件从 Cloud Storage 下载到本地文档文件夹:

//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');
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以找到此内容,并在此页面上阅读有关它的更多信息:https ://firebase.flutter.dev/docs/storage/usage

要在 onPressed 函数上实现它,我建议将该函数与按钮放在同一个类中,并从 onPressed 执行该函数,如下所示:

onPressed: () {
  downloadFileExample();
}
Run Code Online (Sandbox Code Playgroud)